HOWTO parse command line options with Ruby Slop

Learn how to parse command line options in your Ruby scripts with the slop gem, an alternative to Ruby’s built-in OptionParser class.

Installing the slop gem

Make sure you have the slop gem installed:

gem install slop

Alternatively add the gem to your Gemfile and install it via bundler.

Parsing command line options

Start by requiring slop, and calling the Slop.parse method with a block that defines which options your script accepts. For example:

require 'slop'

options = Slop.parse do |opts|
  opts.bool '-i', '--include', 'Include protocol headers'
  opts.bool '-v', '--verbose', 'Make the operation more talkative'
  opts.string '-m', '--message', 'Use the given message'

Slop supports the same as OptionParser: single character "short" options (-i), multi-character "long" options (--include), multiple single character options specified together (-iv), negative forms of boolean options (--no-verbose), and both styles of options with arguments (either --message=Hey or --message Hello).

Unlike with OptionParser there’s no need to specify [no-] or option arguments.

Result objects

Slop returns parsed options wrapped up in Slop::Result objects.

# ruby script.rb --include foo bar

options[:include]  # => true

options.verbose?  # => false

options.arguments  # => ["foo", "bar"]

As well as supporting hash-like key lookup these result objects provide some additional helper methods like query methods for boolean options, and an #arguments method which returns any remaining arguments that aren’t options.

Argument type coercion

Type coercion is supported by using the Slop::Options type methods:

options = Slop.parse do |opts|
  opts.integer '-p', '--port', 'Define the port'
  opts.array '-n', '--names', 'Define the list of names'

With this example a port argument will be coerced into an integer, and a comma separated names argument will be coerced into an array of strings.

Slop supports string options, boolean options, integer options, float options, array options, regexp options, as well as custom options.

Displaying a help summary

Slop can be used to automatically generate a "help" or "usage" summary using the given argument descriptions. Simply define a help option and puts the Slop::Options object, or puts the returned Slop::Result object like this:

puts options

You can use Slop::Options#banner= to change the banner message.