Hi Max,
In my app, a Story has a summary field, and on the page that lists
stories, i want to show the first 'n' (eg twenty) words from the summary
(which i would follow with "...").Does anyone know a simple way to do this? I can think of complicated
and ugly ways to do it, involving going through the string a char at a
time counting spaces, but i'm guessing there's a neat rails helper
(since there usually is!).
I usually go for the roll-your-own method, something like this should work nicely for you, just pop the method in your application_helper and call it in your views.
def first_x_words(str,n=20,finish='…')
str.split(' ')[0,n].inject{|sum,word| sum + ' ' + word} + finish
end
my_string = 'Praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi nam! Modo typi qui nunc nobis videntur parum clari fiant sollemnes?'
p first_x_words(my_string) # => "Praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi nam! Modo typi qui nunc nobis videntur parum clari…"
p first_x_words(my_string, 5, '!!!') # => "Praesent luptatum zzril delenit augue!!!"
Hope this helps.
Douglas F Shearer
dougal.s@gmail.com
http://douglasfshearer.com