15

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)
hippietrail
  • 15,848
  • 18
  • 99
  • 158
BSG
  • 1,382
  • 4
  • 14
  • 25

6 Answers6

35

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"]
Simon Woker
  • 4,994
  • 1
  • 27
  • 41
  • 1
    I would like to add that you can supply a separator to the split function. Default the function uses whitespaces, but you might want to split on something else, like slashes or dashes. Ref: http://ruby-doc.org/core-2.2.0/String.html#method-i-split – Jeroen Bouman Jun 09 '16 at 05:47
3
array_of_strings = ["test 1", "test 2", "test 3"]
array_of_strings.map{|str| str.split.last} #=> ["1","2","3"]
megas
  • 21,401
  • 12
  • 79
  • 130
1

The problem with all of these solutions is that you only considering spaces for word separation. Using regex you can capture any non-word character as a word separator. Here is what I use:

str = 'Non-space characters, like foo=bar.'
str.split(/\W/).last
# "bar"
Nick Gronow
  • 1,597
  • 14
  • 14
1
["one two",­ "thre­e four five"­].collect { |s| s.spl­it.last }
=> ["two", "five"]
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
1

"a string of words!".match(/(.*\s)*(.+)\Z/)[2] #=> 'words!' catches from the last whitespace on. That would include the punctuation.

To extract that from an array of strings, use it with collect:

["a string of words", "Something to say?", "Try me!"].collect {|s| s.match(/(.*\s)*(.+)\Z/)[2] } #=> ["words", "say?", "me!"]

DGM
  • 26,629
  • 7
  • 58
  • 79
0

This is the simplest way I can think of.

hostname> irb
irb(main):001:0> str = 'This is a string.'
=> "This is a string."
irb(main):002:0> words = str.split(/\s+/).last
=> "string."
irb(main):003:0> 
Dylan Northrup
  • 161
  • 1
  • 9