OneBite.Dev - Coding blog in a bite size

reverse a string in Ruby

Code snippet on how to reverse a string in Ruby

  def reverse_string(string)
    reversed_string = ""
    c = string.length - 1 
    while c >= 0 
      reversed_string += string[c] 
      c -= 1
    end
    return reversed_string
  end

This code reverses a string by looping over each character of the string in reverse order. First, the code defines a function named reverse_string which takes a string as an argument. Then a reversed_string variable is declared empty, as a placeholder for the reversed string. Next, a counter c is set to the length of the string minus 1 since indexing in Ruby starts at 0. The while loop will loop through each character of the string in reverse order, by subtracting 1 from the counter each iteration. reversed_string is then appended with the character at the current index of the string. The while loop will run until c is 0, at which point the reversed_string is returned.

ruby