From: Robert Klemme Date: 2010-02-10T07:15:12+09:00 Subject: Re: OptionParser does not enforce required argument On 02/09/2010 08:22 PM, Sean Smitz wrote: > I'm not seeing the difference between specifying a required argument and > an option argument in OptionParser other than they used '<<' in the > assignment of the former. "Mandatory" refers to the argument to an option - not the presence of the option as such. Quoting the docs # Mandatory argument. opts.on("-r", "--require LIBRARY", "Require the LIBRARY before executing your script") do |lib| options.library << lib end # Optional argument; multi-line description. opts.on("-i", "--inplace [EXTENSION]", "Edit ARGV files in place", " (make backup if EXTENSION supplied)") do |ext| options.inplace = true options.extension = ext || '' options.extension.sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot. end Option -r needs an argument (the library) while option -i can go without. Example: irb(main):004:0> OptionParser.new do |o| irb(main):005:1* o.on '-i NAME' do |x| p x end irb(main):006:1> end.parse ["-i", "xx"] "xx" => [] irb(main):007:0> OptionParser.new do |o| irb(main):008:1* o.on '-i NAME' do |x| p x end irb(main):009:1> end.parse ["-i"] OptionParser::MissingArgument: missing argument: -i from (irb):7 from /usr/local/bin/irb19:12:in `
' irb(main):010:0> OptionParser.new do |o| irb(main):011:1* o.on '-i [NAME]' do |x| p x end irb(main):012:1> end.parse ["-i"] nil => [] irb(main):013:0> If you want to ensure that an option is present (which is somewhat contradictory, there is a reason they are called "options") you can assign the argument (or a value provided) to a variable and check that variable for nil after option processing. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/