Home »
Ruby programming »
Ruby programs
Ruby program to reverse a string | Set 2
Ruby | Reversing string: Here, we are going to learn different ways to reverse a string in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on April 10, 2020
Ruby | Reversing string
Here, we are implementing a Ruby program to reverse a string.
Methods used:
- gets: This method is a public instance method of String class which is used to take input from the console.
- puts: This method is a public instance method of String class which is used to print Strings on the console.
- reverse: This method is a public instance method of String class which is used to reverse the String object.
- split: This method is a public instance method of String class which is used to convert the String into array instance.
- length: This method is a public instance method of String class which is used to find the number of characters present in the String.
- times: This is a kind of loop through which the statement iterates for a given number of times.
- push: This method is used to add character to the array object.
- pop: This method is used to remove the character from the array object.
- join: This method is used to covert the Array object into the String.
Example 1: Without using library method reverse
=begin
Ruby program to reverse a String.
=end
def rev_str(str)
s_str = str.split("")
new_str = []
str.length.times{new_str.push(s_str.pop)}
new_str.join
end
puts "Enter the String you want to reverse:"
string = gets.chomp
puts "The reversed String is #{rev_str(string)}"
Output
Enter the String you want to reverse:
includehelp.com
The reversed String is moc.plehedulcni
Explanation:
In the above code, you can observe that we have defined a function that is responsible for reversing the String object. First, we have converted the String into an Array object then after processing it, we have converted it back to a String object.
Example 2:
=begin
Ruby program to reverse a String.
=end
puts "Enter the String you want to reverse:"
string = gets.chomp
rev_string = string.reverse
puts "The reversed String is #{rev_string}"
Output
RUN 1:
Enter the String you want to reverse:
includehelp.com
The reversed String is moc.plehedulcni
RUN 2:
Enter the String you want to reverse:
Hello World!
The reversed String is !dlroW olleH
Explanation:
In the above code, you can observe that we have invoked the method reverse which is a public instance method defined in Ruby's library for reversing the String. For creating the permanent changes in the String you can invoke reverse! method.