Iggy Iggy - 5 months ago 9
Ruby Question

Recursive string modification in Ruby

I have a string. I need to make every other line reversed. If count is 2, it should display:

"Hola mi amigo \nogima im aloH"


If count is 3, it should display:

"Hola mi amigo \nogima im aloH \nHola mi amigo"


and so on. What is the shortest way to perform string modification between every other
"\n"
?

My hunch is to use regex. In addition to regex solution, is there any non-regex solution? I would like to see both for comparison.

def hola(count)
if COUNT IS LESS THAN 2
return false
elsif ODD
(("Hola mi amigo ")*((count-1)/2) + "\n") * count
elsif EVEN
(("Hola mi amigo ")*(count/2) + "\n") * count
end
end

Answer

If there are no restrictions in the implementation, then try something like this:

string = "Hola mi amigo"
count.times.map { |i| i.odd? ? string.reverse : string }.join "\n"

times.map will create an enumerator. The next block will check if the current index is odd or even; in the first case, it will reverse the string, and return it. Finally, all strings are concatenated together with join (with newlines).

Also, here is another (and probably less efficient) solution (recursive):

def hola(count)
  if count == 0
    ''
  elsif count.even?
    "Hola mi amigo".reverse + "\n" + hola(count - 1)
  else
    "Hola mi amigo" + "\n" + hola(count - 1)
  end
end
Comments