Pouya
Pouya

Reputation: 65

How to reverse a string using each method?

So here is the string I want to convert to an array, where then I want to reverse each word without reversing the entire sentence, and then join them back and provide the output.

For instance, I want to change "Hello there, and how are you?" to "olleH ,ereht dna woh era ?uoy"

This is the string:

sentence1="Hello there, and how are you?"

and, this is my code in which I have to incorporate .each(which i know is wrong, but don't know how)

def reverse_each_word(sentence1)
  split_array = sentence1.split
  reversed_array = split_array.reverse
  reversed_array.each do |joined_array|
    joined_array.join(' ')
  end
end

and as mentioned, the desired result has to be:

"olleH ,ereht dna woh era ?uoy"

Upvotes: 0

Views: 315

Answers (2)

Sebastián Palma
Sebastián Palma

Reputation: 33471

You're calling join in a string, since you're iterating over each element in reversed_array, and all those ones are string objects:

p sentence1.split.first.join(' ')
# undefined method `join' for "Hello":String (NoMethodError)

It might work if you use something to store the value in each iteration within the block, it can be a variable declared outside the iteration, or better map, after that, you can just reverse each string and then join everything:

def reverse_each_word(sentence1)
  sentence1.split.map do |joined_array|
    joined_array.reverse
  end.join(' ')
end

p reverse_each_word(sentence1) # "olleH ,ereht dna woh era ?uoy"

Notice this can be written as sentence1.split.map(&:reverse).join(' ') too.


In case you're looking for each to solve this problem, you'll need a variable where to store each "modified" string as long as you're iterating over each of those elements:

memo = ''
sentence1.split.each { |joined_array| memo << "#{joined_array.reverse} " }
p memo.rstrip # "olleH ,ereht dna woh era ?uoy"

There you have a memo variable which is an empty string, just for the reason to be filled with each reversed string, you reverse the string and add a white space to the right. The last string is going to have an additional whitespace, so rstrip helps you to "remove" it.

For collect you can use the map approach, because they're aliases.

Upvotes: 3

Cary Swoveland
Cary Swoveland

Reputation: 110755

I would be inclined to use String#gsub with a regular expression.

str = "Hello there, and how are you?"

str.gsub(/\S+/) { |s| s.reverse }
  #=> "olleH ,ereht dna woh era ?uoy"

The regular expression reads, "match one or more characters other than whitespace characters".

Upvotes: 2

Related Questions