By Alvin Alexander. Last updated: June 4, 2016
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:
- How to read command line arguments in Perl
- How to read command line arguments in PHP
- How to read command line arguments in a Unix/Linux shell script