Feature #11191
Updated by nobu (Nobuyoshi Nakada) over 9 years ago
Simply collecting configuration values is a very popular use for OptionParser. Code like this is quite common: ~~~ruby ~~~ config = {} opts = OptionParser.new do |o| o.on "-h", "--host=HOST", "hostname" do |h| config[:host] = h end o.on "-p", "--port=PORT", "port", Integer do |p| config[:port] = p end o.on "-v", "--verbose" do config[:verbose] = true end o.on "-q", "--quiet" do config[:quiet] = true end end opts.parse! # do something with config values ~~~ This boilerplate is one of the reasons I built Slop: https://github.com/leejarvis/slop I'd like to add a `to_h` method to OptionParser which returns a Hash containing the switch name and switch argument values. This would reduce the above example to: ~~~ruby ~~~ opts = OptionParser.new do |o| o.on "-h", "--host=HOST", "hostname" o.on "-p", "--port=PORT", "port", Integer o.on "-v", "--verbose" o.on "-q", "--quiet" end ~~~ With this example, the output would look something like: ~~~ruby ~~~ opts.parse %w(--host localhost --port 8000 --verbose) puts opts.to_h #=> {:host=>"localhost", :port=>8000, :verbose=>true, :quiet=>nil} ~~~ I've attached a patch that implements this functionality in quite a basic way. I'm very keen to hear what others think.