Getoptlong

The GetoptLong class allows you to parse command line options similarly to the GNU getopt_long() C library call. Note, however, that GetoptLong is a pure Ruby implementation.

GetoptLong allows for POSIX-style options like --file as well as single letter options like -f

The empty option -- (two minus symbols) is used to end option processing. This can be particularly important if options have optional arguments.

Installation

Add this line to your application's Gemfile:

gem 'getoptlong'

And then execute:

$ bundle

Or install it yourself as:

$ gem install getoptlong

Usage

require 'getoptlong'

opts = GetoptLong.new(
  [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
  [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
  [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
)

dir = nil
name = nil
repetitions = 1
opts.each do |opt, arg|
  case opt
    when '--help'
      puts "hello [OPTION] ... DIR\n-h, --help:\n   show help\n--repeat x, -n x:\n   repeat x times\n--name [name]:\n   greet user by name, if name not supplied default is John\nDIR: The directory in which to issue the greeting.\n      EOF\n    when '--repeat'\n      repetitions = arg.to_i\n    when '--name'\n      if arg == ''\n        name = 'John'\n      else\n        name = arg\n      end\n  end\nend\n\nif ARGV.length != 1\n  puts \"Missing dir argument (try --help)\"\n  exit 0\nend\n\ndir = ARGV.shift\n\nDir.chdir(dir)\nfor i in (1..repetitions)\n  print \"Hello\"\n  if name\n    print \", \#{name}\"\n  end\n  puts\nend\n"

Example command line:

hello -n 6 --name -- /tmp

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake test to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/ruby/getoptlong.