I managed to cobble together this statement based on lots of help and copying and pasting. It basically returns the first x number of words in a string and im using it as a helper in my app.
Could someone please help me understand how I would add a condition to say if the actual string is less than x words don’t add the finishing bit (which is a …). So in the equation below I’ like the ‘finish’ section to only be added if they are more than the number of words passed into the equation.
def first_x_words(str,n=20,finish='…')
str.split(' ')[0,n].inject{|sum,word| sum + ' ' + word} + finish
end
Actually – if I could make it more complicated, is it possible, after I find a condition where there are less than x words, to check to see if the last 4 characters are </p> and if they are, remove them.
Thanks,
Adam
This should do what you’re looking for: