Handling command line arguments in Ruby with optparse

I make a lot of little command line utility programs as I hack on things, but usually I need to pass in some sort of flag or argument into it.

I usually just use the ARGV array like so:

name = ARGV[0]
age = ARGV[1]

but sometimes we want to skip the first argument and only provide the second one which can be tricky to do if we only rely on the ARGV array.

Ruby has the optparse library as part of the standard library which means we need to require it, but it won’t actually install an external gem for it.

require 'optparse'

options = {} do |opts|
  opts.banner = "Usage: app.rb [options]"

  opts.on("-n", "--name=NAME", "First name of user") do |n|
    args[:name] = n

  opts.on("-a", "--age=AGE", "Age of user") do |a|
    args[:age] = a


if args[:name]
  puts "NAME: #{args[:name]}"

if args[:age]
  puts "AGE: #{args[:age]"

Now if you run the app with the -h flag it will print out the options for you for free:

ruby app.rb -h
Usage: app.rb [options]
    -n, --name=NAME                  First name of user
    -a, --age=AGE                    Age of user

We can run our app now and pass in just a single argument without having to worry about the order like we did when we relied on ARGV

ruby app.rb -a 34
AGE: 34