Reputation: 11
I am trying to reverse each word of a string.
def reverse(string)
words=string.split(" ")
words.each do |word|
new_string = word.reverse!.join(" ")
end
end
reverse('hello from the other side')
Can someone tell me why this isn't working?
Upvotes: 0
Views: 55
Reputation: 110685
.join(" ")
is in the wrong place. Move it to the end of your penultimate line:
def reverse(string)
words=string.split(" ")
words.each do |word|
word.reverse!
end.join(" ")
end
reverse('hello from the other side')
#=> "olleh morf eht rehto edis"
I removed new_string =
because it does nothing.
As you gain experience with Ruby you will find you could write this more compactly as follows:
def reverse(string)
string.split.map(&:reverse).join(" ")
end
Upvotes: 2