Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 897
BSG Avatar asked Mar 02 '12 13:03

BSG


People also ask

How do you find the last word in a string?

Get the Last Word from a String #Call the split() method on the string, passing it a string containing an empty space as a parameter. The split method will return an array containing the words in the string. Call the pop() method to get the value of the last element (word) in the array.

How do I extract the last word from a string in Python?

To get the last word from a string, we have to convert the string into a list at the first. After converting the string into a list, simply we can use the slicing operator to get the last word of the string and then we can print it. For converting a string into a list we can simply use the split() method.


2 Answers

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"]
like image 97
Simon Woker Avatar answered Sep 29 '22 09:09

Simon Woker


array_of_strings = ["test 1", "test 2", "test 3"]
array_of_strings.map{|str| str.split.last} #=> ["1","2","3"]
like image 24
megas Avatar answered Sep 29 '22 10:09

megas