From: 7stud -- Date: 2007-10-09T01:46:25+09:00 Subject: Re: optparse and required switches Roger Nordqvist wrote: > Hi ... > > Im lost with optparse. > > Got a couple of questions if its OK. > > 1. I've been reading the documentation but I cant get it into my thick > head how I tell an option that it is required or optional? I guess all > opts are optional initially, but how do I say that an option is > required. > > 2. How do I gracefully tell the user that an option they provided is > non-existent. I dont want ruby to crash with a big bang and a lot of > error output. > > At at last I would like to appologies if this are noobish questions. Im > new to ruby and Im struggling to get a hang of it. But I dont read ruby > code flawlessly and I dont always get the examples that the gems provide > me. > Try something like this: require 'optparse' opts = OptionParser.new do |opts| #value for option is required: opts.on("-t=ARG") do |val| puts "-t option entered with value=#{val}" end #value for option is optional: opts.on("-y [=RANDOM_CHARS]") do |val| puts "-y option entered with value=#{val}" end end begin #option -t is required: #---------------------- found_opt_t = false ARGV.each do |word| if word[0, 2] == '-t' found_opt_t = true end end if not found_opt_t puts "Option -t is required. Exiting..." exit end #---------------------- opts.parse!(ARGV) rescue OptionParser::MissingArgument => e puts e.to_str.capitalize.gsub("argument:", "value for:") puts "That option requires a value. Please try again." puts "Exiting.." exit end Test run: $ ruby r8test.rb -t 10 -y 15 -t option entered with value=10 -y option entered with value=15 $ ruby r8test.rb -t10 -t option entered with value=10 $ ruby r8test.rb -t Missing value for: -t That option requires a value. Please try again. Exiting.. $ ruby r8test.rb Option -t is required. Exiting... $ -- Posted via http://www.ruby-forum.com/.