Skip to content
Daniel Berger edited this page May 4, 2023 · 8 revisions

Overview

The getopt gem is a simple command line parsing library. It provides two classes - Getopt::Long and Getopt::Std.

Installation

gem install getopt

Using Getopt::Std

require 'getopt/std'
	
# Look for -o with argument, and -I and -D boolean arguments
opt = Getopt::Std.getopts("o:ID")

if opt["I"]
  # Do something if -I passed
end
		
if opt["D"]
  # Do something if -D passed
end
		
if opt["o"]
  case opt["o"]
    # blah, blah, blah
  end
end

# Look for multiple switches that require arguments
opt = Getopt::Std.getopts('d:r:c:') # -d, -r and -c all require an argument.

Using Getopt::Long

require 'getopt/long'

opt = Getopt::Long.getopts(
  ["--foo", "-f", Getopt::BOOLEAN],
  ["--bar", "-b", Getopt::REQUIRED]
)
   
# Or, to save your fingers some typing:

require "getopt/long"
include Getopt

opt = Long.getopts(
  ["--foo", "-f", BOOLEAN],
  ["--bar", "-b", REQUIRED]
)

if opt["foo"]
  # Do something if --foo or -f passed
end

if opt["b"]
  # Do something if --bar or -b passed
end

Motivation

When this library was originally written, the command line parsing libraries available for Ruby were extremely limited and caught up in academic justifications for not subclassing the Hash class. The result, in practice, was that everyone would immediately convert everything into a hash manually within their code. With this library you no longer have to fiddle with that, because you're dealing with a hash.

Other more feature-filled command line libraries have come along since then, but I still use this for its simplicity. I hope you find it easy to use as well.

Clone this wiki locally