[#69616] [Ruby trunk - Feature #11258] add 'x' mode character for O_EXCL — cremno@...
Issue #11258 has been updated by cremno phobia.
3 messages
2015/06/16
[#69643] [Ruby trunk - Misc #11276] [RFC] compile.c: convert to use ccan/list — normalperson@...
Issue #11276 has been updated by Eric Wong.
3 messages
2015/06/17
[#69751] [Ruby trunk - Bug #11001] 2.2.1 Segmentation fault in reserve_stack() function. — kubo@...
Issue #11001 has been updated by Takehiro Kubo.
3 messages
2015/06/27
[ruby-core:69437] [Ruby trunk - Feature #11191] Add #to_h method to OptionParser
From:
nobu@...
Date:
2015-06-02 01:26:18 UTC
List:
ruby-core #69437
Issue #11191 has been updated by Nobuyoshi Nakada.
Lee Jarvis wrote:
> Yes exactly. This will remove much of the boilerplate I mentioned above. However, the functionality should be exposed (I'm not sure if your code was suggesting that this is a documentable feature or just a workaround). This is made a little more difficult with the design that an `OptionParser` instance should not be modified at parse time. Do you have any other ideas for a workaround?
An idea is to add an keyword argument to `OptionParser#parse` and so on.
----------------------------------------
Feature #11191: Add #to_h method to OptionParser
https://bugs.ruby-lang.org/issues/11191#change-52709
* Author: Lee Jarvis
* Status: Feedback
* Priority: Normal
* Assignee: Nobuyoshi Nakada
----------------------------------------
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.
---Files--------------------------------
0001-Add-to_h-method-to-OptionParser.patch (2.97 KB)
--
https://bugs.ruby-lang.org/