【发布时间】:2011-08-13 07:03:52
【问题描述】:
<%= message.content %>
我可以显示这样的消息,但在某些情况下我想只显示字符串的前 5 个单词,然后显示一个省略号 (...)
【问题讨论】:
-
什么是“词”?
mother-in-law是一字还是三字?co-ordinate怎么样?
标签: ruby-on-rails ruby string
<%= message.content %>
我可以显示这样的消息,但在某些情况下我想只显示字符串的前 5 个单词,然后显示一个省略号 (...)
【问题讨论】:
mother-in-law 是一字还是三字? co-ordinate 怎么样?
标签: ruby-on-rails ruby string
在 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 %>
但常用的方法是truncate方法
# Message helper
def content_excerpt(c)
return unless c
truncate(c, :length => 20)
end
【讨论】: