Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created September 26, 2011 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rklemme/1241917 to your computer and use it in GitHub Desktop.
Save rklemme/1241917 to your computer and use it in GitHub Desktop.
Simple option parsing
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"]
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