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.
Add this line to your application's Gemfile:
gem'getoptlong'And then execute:
$ bundle
Or install it yourself as:
$ gem install getoptlong
require'getoptlong'opts=GetoptLong.new(['--help','-h',GetoptLong::NO_ARGUMENT],['--repeat','-n',GetoptLong::REQUIRED_ARGUMENT],['--name',GetoptLong::OPTIONAL_ARGUMENT])dir=nilname=nilrepetitions=1opts.eachdo |opt,arg|
caseoptwhen'--help'puts<<-EOFhello [OPTION] ... DIR-h, --help: show help--repeat x, -n x: repeat x times--name [name]: greet user by name, if name not supplied default is JohnDIR: The directory in which to issue the greeting. EOFwhen'--repeat'repetitions=arg.to_iwhen'--name'ifarg == ''name='John'elsename=argendendendifARGV.length != 1puts"Missing dir argument (try --help)"exit0enddir=ARGV.shiftDir.chdir(dir)foriin(1..repetitions)print"Hello"ifnameprint", #{name}"endputsendExample command line:
hello -n 6 --name -- /tmp
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.
Bug reports and pull requests are welcome on GitHub at https://github.com/ruby/getoptlong.