Ruby command line arguments By Alvin Alexander. Last updated: June 3 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.
- 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:
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.
- 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:
input_file = ARGV[0]
output_file = ARGV[1]