Home > Software engineering >  In Ruby, how to return a sentence with each word reversed in place?
In Ruby, how to return a sentence with each word reversed in place?

Time:04-25

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??

CodePudding user response:

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

CodePudding user response:

def reverse_each_word(string)
  new_array = string.split(" ")
  new_array.collect {|word| word.reverse }.join(" ")
end
  • Related