Question

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)
Was it helpful?

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

OTHER TIPS

array_of_strings = ["test 1", "test 2", "test 3"]
array_of_strings.map{|str| str.split.last} #=> ["1","2","3"]
["one two",­ "thre­e four five"­].collect { |s| s.spl­it.last }
=> ["two", "five"]

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

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> 

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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top