2012-03-02 8 views

답변

26

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

구두점을 제외 할 잘 작동한다, delete 그것을

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

배열에서 배열로 "마지막 말"을 얻으려면 당신 collect

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

완벽 해요, 제대로 된 상태였습니다. 감사! – BSG

+1

분할 함수에 구분 기호를 제공 할 수 있다고 덧붙이고 싶습니다. 기본 함수는 공백을 사용하지만 슬래시 나 대시와 같은 다른 항목으로 분할 할 수도 있습니다. 참고 문헌 : 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!' 마지막 공백의 캐치. 그것은 구두점을 포함 할 것입니다.

는 수집와 함께 사용, 문자열 배열에서 해당 압축을 풀려면 :

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

0

이것은 내가 생각할 수있는 가장 간단한 방법입니다.

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> 
관련 문제