From: sto.mar@... Date: 2012-08-04T03:21:57+09:00 Subject: Re: OptionParser error handling (InvalidArgument) It is not clear to me what your problem is. Slightly adapted from the post cited by you: ----- require 'optparse' options = {} opts = OptionParser.new do |opts| # Cast 'no' argument to an Integer. opts.on('-n', '--no N', Integer, 'Number of...') do |no| options[:no] = no end end opts.parse!(ARGV) p options ----- results (as it should) in $ ruby optparse.rb -n 34 {:no=>34} $ ruby optparse.rb -n duck optparse.rb:12:in `
': invalid argument: -n duck (OptionParser::InvalidArgument) Am 03.08.2012 18:03, schrieb Panagiotis Atmatzidis: > ---------------------------------------------------- > # check if options[:no] is interger > > if options[:no] > begin > $no = Integer(options[:no]) > rescue ArgumentError > puts "#{$no} is not an Integer!" > else > true > end > else > $no = 0 > end This is not necessary, since the option value has already been cast to an integer, or an exception has been raised. Btw, you should not use global variables. > ---------------------------------------------------- > but didn't work. The error I get from cli is: > > f2bread.rb:483:in `
': invalid argument: -s duck (OptionParser::InvalidArgument) > > Apparently I need to somehow handle this from within OptionParser. Any ideas on how to proceed? I found this post[1] online which explains what I want but I couldn't figure how exactly it works. So some actual codes with a sort of explanation of where *exactly* sits on the program (outside or inside "OptionParser.new" class?). > > The relevant OptionParser lines, where is specified that '-n' accepts Integers, are: > ---------------------------------------------------- > opts.on('-n', '--no N', Integer, 'Number of top entries to be displayed. By default all entries are displayed.') do |no| > options[:no] = no > end > ---------------------------------------------------- actually, it *did* work. "duck" is not an integer, so an exception is raised. > [1] http://blog.segment7.net/2008/01/05/optionparser-argument-casting --