Reverse String in Ruby

Published on 24 September 2018 (Updated: 15 May 2023)

Welcome to the Reverse String in Ruby page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

if ARGV.length >= 1
    string = ARGV[0]

    puts string.reverse
end

Reverse String in Ruby was written by:

This article was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

Right away, we begin by checking to see if the user gave us a string in the form of a command line argument:

if ARGV.length >= 1

If not, we exit the program

Otherwise, we store the command line argument that the user passed into a string:

else
    string = ARGV[0]

    puts string.reverse
end

Then, we reverse the string using the built-in method of the string class and print the result onto the screen.

As we can see, our solution is very brief. That's because we're using a high-level language that offers many different tools, so we can concentrate on building our application instead of worrying about implementation details.

How to Run the Solution

If you have Ruby installed on your machine, you can run the following command:

ruby reverse-string.rb SomeStringHere

Alternatively, websites like REPL allow you to run code from several programming languages in your browser. Feel free to leverage one of those!