Let's say that I have a simple Ruby app where I want the first argument (if any) to specify the environment: TEST, DEVELOPMENT or PRODUCTION (with DEVELOPMENT being the default if no argument is given). For instance,
ruby myapp.rb test
would run it in TEST mode. Also, shorthands should be accepted, so that for instance
ruby myapp.rb t
would run the app in TEST mode and
ruby myapp.rb dev
would run it in DEVELOPMENT mode.
I'd like to use OptionParser, but it behaves very weirdly. If myapp.rb is
require 'optparse'
environment = 'DEVELOPMENT'
opts = OptionParser.new
opts.on('test') { environment = 'TEST' }
opts.on('production') { environment = 'PRODUCTION' }
opts.parse!(ARGV)
then environment becomes PRODUCTION no matter what arguments I pass; for some reason, opts.on('production') always executes its block. (It doesn't if I use a flag-style string like '-production' instead.) And there's no way I can see to have OptionParser look for strings starting with 't' rather than the exact string 'test'.
Maybe OptionParser is the wrong tool for the job. Obviously it would be trivial to split up ARGV myself. I'm just wondering what's going on with this behavior. I'm on Ruby 1.9.2.