Home »
Ruby programming »
Ruby programs
Ruby program to reverse a string
Reversing a string in Ruby: Here, we are going to learn how to reverse a given string in Ruby programming language with or without using library method?
Submitted by Hrithik Chandra Prasad, on August 07, 2019
Reversing a string
Given a string and we have to reverse the string in Ruby.
Ruby provides you method reverse to reverse a string but you can also perform the same functionality by using your code. In the following programs, we have mentioned both the ways through which you can find the reverse of a string.
Methods used:
- puts: Used to convey messages to the user.
- gets: Used to take input from the user.
- .length: Used to get the length of the string.
- .reverse: It is the predefined method specifically defined to find the reverse of a string. You can directly find the reverse of the string using this method in as single code.
Variables used:
- str1: Storing the string provided by the user.
- newstr: Storing the new string which is the reverse of actual string.
Ruby code to reverse a string
Method (1): Without using library method
=begin
Ruby program to reverse a given string.
=end
puts "Enter the String:"
str1=gets.chomp
newstr= ' '
for i in 1..str1.length
newstr+=str1[str1.length - i]
end
puts "The reverse of #{str1} is #{newstr}"
Output
RUN 1:
Enter the String:
Includehelp.com
The reverse of Includehelp.com is moc.plehedulcnI
RUN2:
Enter the String:
Hrithik
The reverse of Hrithik is kihtirH
Method (2): Using the reverse string
=begin
Ruby program to reverse a given string.
=end
puts "Enter the String:"
str1=gets.chomp
newstr=str1.reverse
puts "The reverse of #{str1} is #{newstr}"
Output
RUN 1:
Enter the String:
Includehelp
The reverse of Includehelp is plehedulcnI
RUN 2:
Enter the String:
Haridwar
The reverse of Haridwar is rawdiraH