Austin Stehling Austin Stehling - 28 days ago 10
Ruby Question

How does this iterative reverse method work in Ruby?

I have been building small programs for the last 2 months while also taking a few courses online to help me learn coding. It's been going well and I feel like the question I am about to ask is something simpler than some of the stuff I've written.

Below are two methods to reverse a string. I understand method 2, I do not understand how method 1 works. They both give the same output. Can anyone explain how the first method works?

1.

def reverse(string)
reversed_string = ""

i = 0
while i < string.length
reversed_string = string[i] + reversed_string

i += 1
end

return reversed_string
end


2.

def rev(string)
string.reverse
end

Answer

Lets say string = 'Hello'

When i = 0, string[0] is referring to H and reversed_string is ``. Therefore, after reversed_string = string[i] + reversed_string, reversed_string is H.

i is then incremented.

When i = 1, string[1] is referring to e and reversed_string is H. Therefore, after reversed_string = string[i] + reversed_string, reversed_string is eH. e is concatenated to the front of the reversed_string string.

i is then incremented.

When i = 2, string[2] is referring to l and reversed_string is He. Therefore, after reversed_string = string[i] + reversed_string, reversed_string is leH. l is concatenated to the front of the reversed_string string.

i is then incremented.

The loop continues until i equals string.length, meaning there are no more letters to move to the front.

Comments