e_r e_r - 6 months ago 19
Ruby Question

Ruby: substring to a certain length and also to last whitespace within substring

I am trying to truncate a long string of text to a certain length, but want to also make sure that the truncated result ends at a whitespace. I am also going to append an ellipsis afterwards.

For example this:

"This is a very long string that has more characters than I want in it."


becomes this:

"This is a very long string that..."


I am starting with this but obviously this doesn't deal with the problem of ending the string on whitespace.

<%= item.description[0..30] %>&hellip;

Answer
s[0..30].gsub(/\s\w+\s*$/, '...')

The original answer didn't work in the case where the 30 character substring ended on a whitespace character. This solves that.

>> desc="This is some text it is really long"

>> desc[0..30].gsub(/\s\w+$/,'...')
"This is some text it is really "

>> desc[0..30].gsub(/\s\w+\s*$/,'...')
"This is some text it is..."