Justin Phillip
Justin Phillip

Reputation: 299

Reverse characters in words retaining the order of the words

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

Answers (5)

rohit89
rohit89

Reputation: 5773

str.split(' ').map{|w| w.reverse}.join ' '

Cleaner version:

str.split.map(&:reverse).join ' '

Upvotes: 6

sawa
sawa

Reputation: 168081

Don't know why people insist on using split.

s.gsub(/\w+/, &:reverse)

Upvotes: 6

klaustopher
klaustopher

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

nickgrim
nickgrim

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

Hauleth
Hauleth

Reputation: 23556

You should do:

def backwards(str)
  str.split.map(&:reverse).join(' ')
end

Upvotes: 2

Related Questions