Command Line Arguments in Ruby

Command-line arguments are a common way to parameterize execution of programs. For example, ruby hello.rb uses hello.rb as an argument to the ruby program.

# ARGV provides access to raw command-line arguments. Note that
# ARGV[0] is the first argument to the program, unlike in some
# other languages where it might be the program name.
args_with_prog = [$PROGRAM_NAME] + ARGV
args_without_prog = ARGV

# You can get individual args with normal indexing.
arg = ARGV[2] if ARGV.length > 2

puts args_with_prog
puts args_without_prog
puts arg

To experiment with command-line arguments, you can run the Ruby script directly:

$ ruby command_line_arguments.rb a b c d
["/path/to/command_line_arguments.rb", "a", "b", "c", "d"]
["a", "b", "c", "d"]
c

In Ruby, command-line arguments are accessed through the ARGV array. The program name is available separately through the $PROGRAM_NAME global variable (also accessible as $0).

Ruby doesn’t typically compile to binaries like some other languages, but it’s common to run Ruby scripts directly with the ruby command.

Next, we’ll look at more advanced command-line processing with option parsing libraries in Ruby.