From: Eric Mahurin Date: 2005-09-13T23:58:01+09:00 Subject: yet another simple command-line option parser I just put in a good example for: http://rcrchive.net/rcr/show/317 It is a simple option parser that has option defaults and converts the options to the right type: # these klass.from_s methods are the meat of the RCR def Float.from_s(s);s.to_f;end def Integer.from_s(s);s.to_i;end def Symbol.from_s(s);s.to_sym;end def String.from_s(s);s.to_s;end def Regexp.from_s(s,*other);new(s,*other);end require 'time.rb' def Time.from_s(s,*other);Time.parse(s,*other);end def argv_options(options) i = 0 while arg = ARGV[i] if arg[0]==?- arg.slice!(0) ARGV.slice!(i) break if arg=="-" # -- terminates options opt = arg.to_sym default = options[opt] if default klass = default.class # would need a big case statement w/o RCR 317 options[opt] = klass.from_s(ARGV.slice!(i)) elsif default.nil? raise("unknown option -#{opt}") else # default==false options[opt] = true end else i += 1 end end options end ARGV.replace(%w( -n 4 -multiplier 3.14 -q -title foobar -pattern fo+ -time 5:55PM -method downcase a b c )) # option => default (or false for a flag) argv_options( :n => 1, :multiplier => 1.0, :q => false, :title => "hello world!", :pattern => /.*/, :time => Time.new, :method => :to_s ) If you have an opinion about the usefulness of this RCR, go vote and give a comment. I didn't have an example before to show it in action. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com