I have a list of objects, with one attribue of :text
. I want to print only the first 250 characters of each :text
.
我有一个对象列表,其中一个属性是:text。我只想打印每个文本的前250个字符。
Is there any simple way in Rails to do it?
在Rails中有什么简单的方法吗?
Here's how im doing my iteration:
以下是我的迭代步骤:
-@cows.each do |c|
%tr
%td= c.id
%td= c.description
%td
Where, description
is text.
,描述文本。
2 个解决方案
#1
5
You can use truncate
:
您可以使用截断:
c.description.truncate(250, :separator => ' ')
It will add "..."
automatically for you, and you have the separator option so you don't have to worry about words being chopped in the middle.
它会自动为你添加“…”,你有分隔符选项,这样你就不用担心文字被夹在中间了。
#2
3
Yep, it's just normal Ruby code:
是的,它只是普通的Ruby代码:
%td= c.description[0..249]
string[n..m]
will give you a substring of string
, starting with the n
th element, and ending with the m
th. see http://ruby-doc.org/core-2.0/String.html#method-i-5B-5D
string[n . .m]会给你一个字符串的子字符串,从第n个元素开始,以第m个结束。看到http://ruby doc.org/core - 2.0 - / - string.html # method-i-5B-5D
Although perhaps you should consider whether this code might be better off in your model than in the view?
尽管您可能应该考虑在您的模型中这段代码是否比在视图中更好?
#1
5
You can use truncate
:
您可以使用截断:
c.description.truncate(250, :separator => ' ')
It will add "..."
automatically for you, and you have the separator option so you don't have to worry about words being chopped in the middle.
它会自动为你添加“…”,你有分隔符选项,这样你就不用担心文字被夹在中间了。
#2
3
Yep, it's just normal Ruby code:
是的,它只是普通的Ruby代码:
%td= c.description[0..249]
string[n..m]
will give you a substring of string
, starting with the n
th element, and ending with the m
th. see http://ruby-doc.org/core-2.0/String.html#method-i-5B-5D
string[n . .m]会给你一个字符串的子字符串,从第n个元素开始,以第m个结束。看到http://ruby doc.org/core - 2.0 - / - string.html # method-i-5B-5D
Although perhaps you should consider whether this code might be better off in your model than in the view?
尽管您可能应该考虑在您的模型中这段代码是否比在视图中更好?