Search code examples
rubystringsubstringtext-segmentation

Extract the last word in sentence/string?


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)

Solution

  • 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"]