How can I limit the number of words displayed in a Ruby string?

Ruby code is below:

<%= product.advert_text -%>

What script can limit the number of words?

+3
source share
2 answers

If you want to limit a certain number of words, the easiest way is to split it into a space and then insert the desired number of words back into the line.

<%=product.advert_text.split.slice(0, limit).join(" ") -%>
+8
source

Since you are working with Rails, you can use the truncate method .

So something like:

<%= truncate(product.advert_text, :length => 20) -%>

:length , , ( :omission - . ).

+15

Source: https://habr.com/ru/post/1759432/


All Articles