Ruby command line arguments

Ruby FAQ: How do I read command line arguments in a Ruby script (Ruby command line args)?

To read command line args in a Ruby script, use the special Ruby array ARGV to get the information you need. Here are a few examples.

1) Getting the number of command line args

To get the number of command line arguments passed in to your Ruby script, check ARGV.length, like this:

# quit unless our script gets two command line arguments
unless ARGV.length == 2
  puts "Dude, not the right number of arguments."
  puts "Usage: ruby MyScript.rb InputFile.csv SortedOutputFile.csv\n"
  exit
end

In the case of this script, I am expecting two command line arguments, and if I don't get two args, I exit the script.

2) Getting the value of the Ruby command line args

To work with the actual values of the arguments that are passed into your Ruby program, just treat ARGV as a normal Ruby array, and get the values like this:

# our input file should be the first command line arg
input_file = ARGV[0]

# our output file should be the second command line arg
output_file = ARGV[1]

Related command line arguments tutorials

For other tutorials on reading command line arguments from different programming languages, we have the following tutorials on our website:

 

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.