How can I limit the amount of words displayed from a Ruby string?
the Ruby code is below:
<%= product.advert_text -开发者_运维技巧%>
What script can limit the amount of words?
Since you are working with Rails, you can use the truncate method.
So, something like:
<%= truncate(product.advert_text, :length => 20) -%>
The :length
option sets the # of characters to truncate at & will add ellipses at the end (you can override the default ellipses with the :omission
option - see the documentation on my link).
If you want to limit to a certain number of words, the easiest way is going to be to split on space and then join the desired number of words back into a string.
<%=product.advert_text.split.slice(0, limit).join(" ") -%>
精彩评论