Ruby - Reverse a String

1. Introduction

Reversing a string is a common task in programming. Whether it's for algorithm challenges, data processing, or string manipulation, knowing different methods to reverse a string can be handy. In this tutorial, we'll explore various ways to reverse a string in Ruby.

2. Program Steps

1. Set up the Ruby development environment.

2. Prompt the user to input a string.

3. Demonstrate multiple methods to reverse the given string.

4. Display the reversed string to the user using each method.

3. Code Program

# Prompting the user for a string
puts "Enter a string to reverse:"
original_string = gets.chomp
# Method 1: Using the built-in reverse method
reversed_string_1 = original_string.reverse
puts "Reversed using method 1: #{reversed_string_1}"
# Method 2: Using a loop
reversed_string_2 = ""
original_string.chars.each { |char| reversed_string_2 = char + reversed_string_2 }
puts "Reversed using method 2: #{reversed_string_2}"
# Method 3: Using inject
reversed_string_3 = original_string.chars.inject { |acc, char| char + acc }
puts "Reversed using method 3: #{reversed_string_3}"

Output:

Enter a string to reverse:
hello
Reversed using method 1: olleh
Reversed using method 2: olleh
Reversed using method 3: olleh

Explanation:

1. gets: Captures user input. By default, the input is taken as a string.

2. chomp: Removes the newline character, which is added when the user hits Enter.

3. reverse: This is Ruby's built-in method for strings. It returns a new string where the characters are in reverse order.

4. chars: Converts a string into an array of characters.

5. each: An iterator method to loop through each character of the string. In the context of method 2, for every character, we prepend it to the reversed_string_2 thus achieving the reversed string.

6. inject: A method that combines the elements of an array by applying a binary operation. In the context of method 3, it's used to accumulate characters in reverse order.


Comments