xuanyinwen
xuanyinwen

Reputation: 73

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?

Upvotes: 3

Views: 3160

Answers (2)

Brian
Brian

Reputation: 6840

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).

Upvotes: 15

Chris Heald
Chris Heald

Reputation: 62648

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(" ") -%>

Upvotes: 8

Related Questions