ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Ruby String Reversal

Ruby

Goal -- WPM

Ready
Exercise Algorithm Area
1def reverse_string(str)
2return "" if str.nil? || str.empty?
3
4reversed = ""
5index = str.length - 1
6
7while index >= 0
8reversed += str[index]
9index -= 1
10end
11
12reversed
13end
Algorithm description viewbox

Ruby String Reversal

Algorithm description:

This Ruby method reverses a given string. It iterates through the string from the last character to the first, appending each character to a new string. This is a fundamental operation used in various text processing tasks, such as palindrome checking or data scrambling.

Algorithm explanation:

The `reverse_string` method takes a string as input and returns its reversed version. It first checks for edge cases: if the input string is nil or empty, it returns an empty string. Otherwise, it initializes an empty string `reversed` and an index pointing to the last character of the input string. A `while` loop iterates as long as the index is non-negative. In each iteration, the character at the current index is appended to `reversed`, and the index is decremented. This ensures that characters are added in reverse order. The time complexity is O(n), where n is the length of the string, because each character is processed once. The space complexity is also O(n) due to the creation of the new reversed string.

Pseudocode:

function reverse_string(input_string):
  if input_string is empty or null:
    return empty string
  
  initialize reversed_string as empty string
  initialize index to length of input_string - 1
  
  while index is greater than or equal to 0:
    append character at index from input_string to reversed_string
    decrement index
  
  return reversed_string