×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

Ruby program to reverse a string

Last Updated : December 15, 2025

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.

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

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
Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.