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

use*_*974 13 ruby string ruby-on-rails

<%= message.content %>
Run Code Online (Sandbox Code Playgroud)

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

Rad*_*ika 21

在rails中,4.2您可以使用truncate_words.

'Once upon a time in a world far far away'.truncate_words(4)
=> "Once upon a time..."
Run Code Online (Sandbox Code Playgroud)


gil*_*las 16

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

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

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

如果你想要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...
Run Code Online (Sandbox Code Playgroud)


ndr*_*rix 11

请尝试以下方法:

'this is a line of some words'.split[0..3].join(' ')
=> "this is a line" 
Run Code Online (Sandbox Code Playgroud)


Ana*_*oly 2

   # Message helper
   def content_excerpt(c)
     return unlessc
     c.split(" ")[0..4].join + "..."
   end

   # View
   <%= message.content_excerpt %>
Run Code Online (Sandbox Code Playgroud)

但常见的方式是truncate方法

   # Message helper
   def content_excerpt(c)
     return unless c
     truncate(c, :length => 20)
   end
Run Code Online (Sandbox Code Playgroud)