1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Command-line Arguments in Ruby

Using Command-line Arguments to Communicate With Scripts

By

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. This 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 OS X), it's pretty standard to encounter this type of program.

Providing Command-line Arguments

Command-line arguments are passed to the Ruby program by the shell, the program the excepts 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 how 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 with a space in it to a Ruby program. It seems impossible at first, since the shell separates arguments on spaces. However, 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"

Using 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. The following 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
  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. Command-line Arguments in Ruby

©2014 About.com. All rights reserved.