Reputation: 299
I'm trying to reverse the words of each word in a string of multiple words. For example:
"hi whats up" => "ih stahw pu"
This is as close as I have gotten:
def backwards(s)
s.split.each do |y| y.reverse! end
end
Thing is this returns an array, not a string. I tried adding join(' ')
after reverse!
but that gave me an error.
Upvotes: 1
Views: 143
Reputation: 5773
str.split(' ').map{|w| w.reverse}.join ' '
Cleaner version:
str.split.map(&:reverse).join ' '
Upvotes: 6
Reputation: 168081
Don't know why people insist on using split
.
s.gsub(/\w+/, &:reverse)
Upvotes: 6
Reputation: 6941
You almost got it right ... You have to call join(' ')
on the result of the block
def backwards(s)
s.split.map { |word| word.reverse }.join(' ')
end
Upvotes: 1
Reputation: 5437
You want to join the result of the each
, not the result of the reverse!
. You need:
s.split.each {|y| y.reverse!}.join ' '
Upvotes: 0
Reputation: 23556
You should do:
def backwards(str)
str.split.map(&:reverse).join(' ')
end
Upvotes: 2