Reverse a String in Ruby

Published on 24 December 2018 (Updated: 24 December 2018)

Reverse a String in Ruby

In this article, we’re tackling Reverse a String in Java!

How to Implement the Solution

First, like always, here’s the complete solution:

if ARGV.length < 1
    puts "Usage: ruby reverse-string.rb [string]"
else
    string = ARGV[0]
    puts string.reverse
end

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
    puts "Usage: ruby reverse-string.rb [string]"

If not, we print a usage message which tells the user how to use 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.1

How to Run 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!1


References

  1. N. Nichols, “Reverse a String in Ruby,” The Renegade Coder, 23-Nov-2018. [Online]. Available: https://therenegadecoder.com/code/reverse-a-string-in-ruby/. [Accessed: 24-Dec-2018].  2