다양한 길이와 내용의 문자열이 있습니다.문장/문자열에서 마지막 단어를 추출 하시겠습니까?
이제 각 단어의 길이와 문자열의 길이를 모른 채 각 문자열에서 마지막 단어를 추출하는 쉬운 방법을 찾고 있습니다.
와 유사;
array.each{|string| puts string.fetch(" ", last)
다양한 길이와 내용의 문자열이 있습니다.문장/문자열에서 마지막 단어를 추출 하시겠습니까?
이제 각 단어의 길이와 문자열의 길이를 모른 채 각 문자열에서 마지막 단어를 추출하는 쉬운 방법을 찾고 있습니다.
와 유사;
array.each{|string| puts string.fetch(" ", last)
이
"my random sentence".split.last # => "sentence"
구두점을 제외 할 잘 작동한다, delete
그것을
"my random sentence..,.!?".split.last.delete('.!?,') #=> "sentence"
배열에서 배열로 "마지막 말"을 얻으려면 당신 collect
["random sentence...", "lorem ipsum!!!"].collect { |s| s.split.last.delete('.!?,') } # => ["sentence", "ipsum"]
array_of_strings = ["test 1", "test 2", "test 3"]
array_of_strings.map{|str| str.split.last} #=> ["1","2","3"]
["one two", "three four five"].collect { |s| s.split.last }
=> ["two", "five"]
"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!"]
이것은 내가 생각할 수있는 가장 간단한 방법입니다.
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>
완벽 해요, 제대로 된 상태였습니다. 감사! – BSG
분할 함수에 구분 기호를 제공 할 수 있다고 덧붙이고 싶습니다. 기본 함수는 공백을 사용하지만 슬래시 나 대시와 같은 다른 항목으로 분할 할 수도 있습니다. 참고 문헌 : http://ruby-doc.org/core-2.2.0/String.html#method-i-split –