Created
September 26, 2011 09:20
-
-
Save rklemme/1241917 to your computer and use it in GitHub Desktop.
Simple option parsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
11:15:19 Temp$ ./opt.rb -s abc.def -- -x | |
{:source_path=>"abc.def"} | |
11:15:22 Temp$ ./opt.rb -s abc.def -- -x | |
{:source_path=>"abc.def"} | |
["-x"] | |
11:15:28 Temp$ ./opt.rb -s abc.def | |
{:source_path=>"abc.def"} | |
[] | |
11:15:31 Temp$ ./opt.rb -s abc.def -d . | |
{:source_path=>"abc.def", :dest_path=>"."} | |
[] | |
11:15:36 Temp$ ./opt.rb -s abc.def -d . -v | |
{:source_path=>"abc.def", :dest_path=>".", :verbose=>true} | |
[] | |
11:15:39 Temp$ ./opt.rb -s abc.def -d . -v a b c | |
{:source_path=>"abc.def", :dest_path=>".", :verbose=>true} | |
["a", "b", "c"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'optparse' | |
# Pass a Hash which maps Hash keys to option names | |
def OptionParser.quick!(argv, options) | |
result = {} | |
new do |opts| | |
options.each do |key, op| | |
# prepare key | |
raise ArgumentError, 'Invalid option: %p' % op unless /\A([a-z])(:)?\z/i =~ op | |
has_arg = $2 | |
opt_char = has_arg ? "-#$1 VALUE" : "-#$1" | |
# add option | |
opts.on opt_char, do |v| | |
result[key] = v | |
end | |
end | |
end.parse! argv | |
result | |
end | |
options = OptionParser.quick!(ARGV, | |
:source_path => 's:', | |
:dest_path => 'd:', | |
:verbose => 'v', | |
) | |
p options, ARGV |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment