Reputation: 1452
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)
Upvotes: 16
Views: 16787
Reputation: 1617
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"
Upvotes: 1
Reputation: 5034
This should work just fine
"my random sentence".split.last # => "sentence"
to exclude punctuation, delete
it
"my random sentence..,.!?".split.last.delete('.!?,') #=> "sentence"
To get the "last words" as an array from an array you collect
["random sentence...", "lorem ipsum!!!"].collect { |s| s.split.last.delete('.!?,') } # => ["sentence", "ipsum"]
Upvotes: 36
Reputation: 161
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>
Upvotes: 0
Reputation: 26979
"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!"]
Upvotes: 1
Reputation: 199215
["one two", "three four five"].collect { |s| s.split.last }
=> ["two", "five"]
Upvotes: 1
Reputation: 21791
array_of_strings = ["test 1", "test 2", "test 3"]
array_of_strings.map{|str| str.split.last} #=> ["1","2","3"]
Upvotes: 3