Not sure why this solution on reversing a string works


#1


I'm doing a problem where I'm asked to reverse a string without using the .reverse method. Below is the solution and I'm not sure why it works. The way I'm reading it is - I'm creating an empty array named reverse_string. while i is less than the length of the existing string, the program will add a letter from the existing string and..what exactly? I suppose what I'm trying to say is I don't know how to read the below in a way that makes sense.

def reverse(string)
  reverse_string = ""
	
  i = 0
  while i < string.length
    reverse_string = string[i] + reverse_string
    i+=1
  end

  return reverse_string
end


Replace this line with your code.


#2

Ok, I will try to explain this code to you :slight_smile:

First of all, the while loop goes from the first character of input string to its last character one by one. So, one wouldn't expect the string to be outputted in reverse, but all the magic happens here:

reverse_string = string[i] + reverse_string

To explain this line, I'll simply take a test input string like "Ruby" and manually run the code:

There will be four iterations of the while loop, for each character of string ("Ruby" ) reverse_string is initially empty string.
The first character is added to reverse_string, so reverse_string now equals "R"

Now carefully read this - on the second iteration of the loop, on this line - reverse_string = string[i] + reverse_string, the second character of string ("u") gets added before the previously added character "R" in reverse_string, because string[i] gets added before reverse_string. (Notice: reverse_string = string[i] + reverse_string)
Reread that until it makes sense.

So, now reverse_string becomes "uR".Then, on the third iteration, the string character "b" will be added before reverse_string to become "buR".

The last iteration will then finally yield "yubR".

I hope it helps! :slight_smile: