How To Run Ruby Script From Command Line

Ruby is a popular and versatile programming language that is easy to learn and use. One of the most powerful features of Ruby is its ability to be run directly from the command line. In this tutorial, we will learn how to create and run a Ruby script from the command line. This can be especially useful for automating tasks or quickly testing code.

Prerequisites

To follow this tutorial, you need to have Ruby installed on your machine. If you don’t have it installed, you can download the latest version from the official Ruby website.

Creating a Ruby Script

To create a Ruby script, you can use any text editor to write your code. Save the file with a .rb extension, which stands for “Ruby”. For example, let’s create a simple script that prints “Hello, World!” to the console. Open your text editor and write the following code:

puts 'Hello, World!'
    

Save this file as hello_world.rb in a directory of your choice.

Running the Ruby Script from the Command Line

To run your Ruby script from the command line, follow these steps:

  1. Open your command prompt or terminal.
  2. Navigate to the directory where you saved your Ruby script using the cd command. For example, if you saved your script in a folder called “ruby_scripts” on your desktop, you would enter:

cd ~/Desktop/ruby_scripts

  1. Run your Ruby script by entering ruby followed by the name of your script file, including the .rb extension. For our example, you would enter:

ruby hello_world.rb

The script should execute, and you will see the output “Hello, World!” in your command prompt or terminal.

Conclusion

You have now learned how to create and run a Ruby script from the command line. This is a powerful and efficient way to execute Ruby code, whether you’re creating a full application or just writing some simple automation scripts. The next time you want to run a Ruby script, remember these simple steps and you’ll be up and running in no time!