仅显示rails中字符串的前x个单词

 

我可以显示这样的消息,但在某些情况下我想只显示字符串的前5个单词,然后显示省略号(…)

在rails 4.2您可以使用truncate_words 。

 'Once upon a time in a world far far away'.truncate_words(4) => "Once upon a time..." 

你可以使用truncate来限制字符串的长度

 truncate("Once upon a time in a world far far away", :length => 17, :separator => ' ') # => "Once upon a..." 

使用给定的空格分隔符,它不会削减你的话。

如果你想要5个单词,你可以做这样的事情

 class String def words_limit(limit) string_arr = self.split(' ') string_arr.count > limit ? "#{string_arr[0..(limit-1)].join(' ')}..." : self end end text = "aa bb cc dd ee ff" p text.words_limit(3) # => aa bb cc... 

请尝试以下方法:

 'this is a line of some words'.split[0..3].join(' ') => "this is a line" 
  # Message helper def content_excerpt(c) return unlessc c.split(" ")[0..4].join + "..." end # View <%= message.content_excerpt %> 

但常见的方法是截断方法

  # Message helper def content_excerpt(c) return unless c truncate(c, :length => 20) end