2012-03-02 14 views
11

Ho una matrice di stringhe, di diverse lunghezze e contenuti.Estrai l'ultima parola in stringa/frase?

Ora sto cercando un modo semplice per estrarre l'ultima parola da ciascuna stringa, senza sapere per quanto tempo quella parola è o quanto è lunga la stringa.

qualcosa come;

array.each{|string| puts string.fetch(" ", last) 

risposta

26

Questo dovrebbe funzionare bene

"my random sentence".split.last # => "sentence" 

per escludere la punteggiatura, delete è

"my rando­m sente­nce..,.!?".­split.last­.delete('.­!?,') #=> "sentence" 

per ottenere il "ultime parole" come una matrice da una matrice si collect

["random sentence...",­ "lorem ipsum!!!"­].collect { |s| s.spl­it.last.delete('.­!?,') } # => ["sentence", "ipsum"] 
+0

Perfetto, ero sulla strada giusta. Grazie! – BSG

+1

Vorrei aggiungere che è possibile fornire un separatore alla funzione di divisione. La funzione predefinita usa gli spazi bianchi, ma potresti voler dividere su qualcos'altro, come barre o trattini. Rif: http://ruby-doc.org/core-2.2.0/String.html#method-i-split –

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

"a string of words!".match(/(.*\s)*(.+)\Z/)[2] #=> 'words!' cattura dagli ultimi spazi bianchi. Ciò includerebbe la punteggiatura.

Per estrarre che da un array di stringhe, utilizzarlo con Collect:

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

0

Questo è il modo più semplice che posso pensare.

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>