'In Ruby, how to return a sentence with each word reversed in place?
I want to write a method that takes a string as an argument and returns the same sentence with each word reversed in place.
example:-
reverse_each_word("Hello there, and how are you?")
#=> "olleH ,ereht dna woh era ?uoy"
I tried:
def reverse_each_word(string)
array = []
new_array=array <<string.split(" ")
array.collect {|word| word.join(" ").reverse}
end
but the return is
["?uoy era woh dna ,ereht olleH"]
The whole sentence is reversed and not sure why there is [ ]
any help??
Solution 1:[1]
As an alternative approach, you could use gsub to find all words and reverse them:
str = "Hello there, and how are you?"
str.gsub(/\S+/, &:reverse)
#=> "olleH ,ereht dna woh era ?uoy"
/\S+/ matches one or more (+) non-whitespace (\S) characters
Solution 2:[2]
def reverse_each_word(string)
new_array = string.split(" ")
new_array.collect {|word| word.reverse }.join(" ")
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stefan |
| Solution 2 | Joel Blum |
