Command-Line Arguments in Ruby

Ruby Script Arguments Control RB Files

Male fashion designer working in an office
ONOKY - Eric Audras/Brand X Pictures/Getty Images

Many Ruby scripts have no text or graphical interfaces. They simply run, do their job and then exit. To communicate with these scripts in order to change their behavior, command-line arguments must be used.

The command line is the standard mode of operation for UNIX commands, and since Ruby is used widely on UNIX and UNIX-like systems (such as Linux and macOS), it's pretty standard to encounter this type of program.

How to Provide Command-Line Arguments

Ruby script arguments are passed to the Ruby program by the shell, the program that accepts commands (such as bash) on the terminal.

On the command-line, any text following the name of the script is considered a command-line argument. Separated by spaces, each word or string will be passed as a separate argument to the Ruby program. 

The following example shows the proper syntax to use to launch the test.rb Ruby script from a command-line with the arguments test1 and test2.

$ ./test.rb test1 test2

You may encounter a situation in which you need to pass an argument to a Ruby program but there's a space in the command. It seems impossible at first since the shell separates arguments on spaces, but there is a provision for this.

Any arguments in double quotes will not be separated. The double quotes are removed by the shell before passing it to the Ruby program.

The following example passes a single argument to the test.rb Ruby script, test1 test2:

$ ./test.rb "test1 test2"

How to Use Command-Line Arguments

In your Ruby programs, you can access any command-line arguments passed by the shell with the ARGV special variable. ARGV is an Array variable which holds, as strings, each argument passed by the shell.

This program iterates over the ARGV array and prints out its contents:

#!/usr/bin/env ruby
ARGV.each do|a|
  puts "Argument: #{a}"
end

The following is an excerpt of a bash session launching this script (saved as the file test.rb) with a variety of arguments:

$ ./test.rb test1 test2 "three four"
Argument: test1
Argument: test2
Argument: three four
Format
mla apa chicago
Your Citation
Morin, Michael. "Command-Line Arguments in Ruby." ThoughtCo, Aug. 26, 2020, thoughtco.com/command-line-arguments-2908191. Morin, Michael. (2020, August 26). Command-Line Arguments in Ruby. Retrieved from https://www.thoughtco.com/command-line-arguments-2908191 Morin, Michael. "Command-Line Arguments in Ruby." ThoughtCo. https://www.thoughtco.com/command-line-arguments-2908191 (accessed March 19, 2024).