In this installment of Reverse a String in Every Language, we will be looking at another community contribution from our friend, Noah. They’ve decided to share the solution to Reverse a String in Ruby.
If this is your first time playing around in Ruby, check out our Hello World in Ruby article. After that, why not check out all the Ruby articles we have to offer.
Table of Contents
Reverse a String in Ruby
First, like always, here’s the complete solution:
if ARGV.length < 1 puts "Usage: ruby reverse-string.rb [string]" else string = ARGV 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
else string = ARGV puts string.reverse end
Then, we reverse the string using the builtin 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!
Sample Programs in Every Language
We appreciate that you took some time out of your day to read this article. If you have any feedback, we would love to hear it from you.
As always, if you’d like to stay on top of the latest The Renegade Coder articles, consider becoming a member. Every week, you’ll receive an update with the newest articles.
At any rate, until next time!
Chiropractors get a bad rap, but I find their YouTube content somewhat enjoyable. That said, they absolutely destroyed my YouTube recommendations.
Python is a fun language to learn on its own, but what if we could learn it by doing something even more fun like making Discord bots?