Extract the last word in sentence/string?

BSG picture BSG · Mar 2, 2012 · Viewed 14.4k times · Source

I have an array of strings, of different lengths and contents.

Now i'm looking for an easy way to extract the last word from each string, without knowing how long that word is or how long the string is.

something like;

array.each{|string| puts string.fetch(" ", last)

Answer

Simon Woker picture Simon Woker · Mar 2, 2012

This should work just fine

"my random sentence".split.last # => "sentence"

to exclude punctuation, delete it

"my rando­m sente­nce..,.!?".­split.last­.delete('.­!?,') #=> "sentence"

To get the "last words" as an array from an array you collect

["random sentence...",­ "lorem ipsum!!!"­].collect { |s| s.spl­it.last.delete('.­!?,') } # => ["sentence", "ipsum"]