BSG
BSG

Reputation: 1452

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)

Upvotes: 16

Views: 16787

Answers (6)

Nick Gronow
Nick Gronow

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

Simon Woker
Simon Woker

Reputation: 5034

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

Upvotes: 36

Dylan Northrup
Dylan Northrup

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

DGM
DGM

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

OscarRyz
OscarRyz

Reputation: 199215

["one two",­ "thre­e four five"­].collect { |s| s.spl­it.last }
=> ["two", "five"]

Upvotes: 1

megas
megas

Reputation: 21791

array_of_strings = ["test 1", "test 2", "test 3"]
array_of_strings.map{|str| str.split.last} #=> ["1","2","3"]

Upvotes: 3

Related Questions