Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I am assuming you are using optparse here, although the same technique will work for other option parsing libraries. </p> <p>The simplest method is probably to parse the parameters using your chosen option parsing library and then raise an OptionParser::MissingArgument Exception if the value of host is nil.</p> <p>The following code illustrates</p> <pre><code>#!/usr/bin/env ruby require 'optparse' options = {} optparse = OptionParser.new do |opts| opts.on('-h', '--host HOSTNAME', "Mandatory Host Name") do |f| options[:host] = f end end optparse.parse! #Now raise an exception if we have not found a host option raise OptionParser::MissingArgument if options[:host].nil? puts "Host = #{options[:host]}" </code></pre> <p>Running this example with a command line of </p> <pre><code>./program -h somehost </code></pre> <p>simple displays "Host = somehost"</p> <p>Whilst running with a missing -h and no file name produces the following output</p> <pre><code>./program:15: missing argument: (OptionParser::MissingArgument) </code></pre> <p>And running with a command line of ./program -h produces</p> <pre><code>/usr/lib/ruby/1.8/optparse.rb:451:in `parse': missing argument: -h (OptionParser::MissingArgument) from /usr/lib/ruby/1.8/optparse.rb:1288:in `parse_in_order' from /usr/lib/ruby/1.8/optparse.rb:1247:in `catch' from /usr/lib/ruby/1.8/optparse.rb:1247:in `parse_in_order' from /usr/lib/ruby/1.8/optparse.rb:1241:in `order!' from /usr/lib/ruby/1.8/optparse.rb:1332:in `permute!' from /usr/lib/ruby/1.8/optparse.rb:1353:in `parse!' from ./program:13 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload