Skip to main content
Ruby

Ruby – Processing and checking all ARGV entries

By October 13, 2013September 12th, 2022No Comments



We have seen previously in my examples that we can process a single argument passed through to a ruby script. In this tutorial we are going to look at checking that we actually do have arguments to deal with and then processing each argument in turn.

First we need to check that that at least one argument is supplied to the script:

if ARGV.empty?
  puts "Usage: #{__FILE__} <name>"
  puts "At least one argument is required"
  exit(2)
end

We the above block we test for the array ARGV being empty, if it is we then print the message and exit with an error code of 2. Using the variable __FILE__ we can print the name of the script in the usage message. This replaces $0 in other languages.

Now that we can successfully determine that we have at least one argument we may choose to process more than one argument if they exist. We do not need to know in advance how many arguments there are, we can process them one by one by using the each method of the ruby array ARGV.

ARGV.each do | a |
  puts "Hello #{ a.capitalize } "
end #end do block

We can now see that we can process each entry in the array quite simply. In the example we are creating a local variable named a that will match to each argument in the array as we step through.

We can now run the script as

./h2.rb fred
./h2.rb fred bill
./h2.rb fred bill saLLy

and the output will reflect the capitalized version of each name.