Re: optparse question: how to warn of missing positional arguments
Jeremy Bopp <[email protected]>
| Newsgroups | gmane.comp.lang.ruby.general |
|---|---|
| Message-ID | <CA+=tguzhgrMEtVJK_6-RD+4PDDnMiXn9HZkrt_KwVThcPHgs+w@mail.gmail.com> |
After the option parser has completed parsing arguments, it will leave any
non-option arguments in the argument array. You can check that the array
is empty and then print the help message and exit. The key is to preserve
a reference to the parser object so that you can call #to_s on it later to
emit the usage output when needed. Below is an example largely lifted from
the documentation for the optparse library which will do what I believe you
are asking about:
example.rb
-------------------------------------------
require 'optparse'
option = false
parser = OptionParser.new do |opts|
opts.banner = 'Usage example.rb [options] REQUIRED_ARG'
opts.separator ''
opts.on('-a', '--an-option', 'An example option') do |val|
option = val
end
opts.on('-h', '--help', 'Prints this help') do
puts opts
exit
end
end
parser.parse!
if ARGV.empty?
puts parser
exit 1
end
p option
p ARGV
-Jeremy
On Fri, Mar 22, 2019 at 2:49 PM Artie Ziff <[email protected]> wrote:
> Hello,
>
> My goal is to force a display of the banner (usage string) when a
> positional parameter is not present; in the sense of ARGV[1] == nil
>
> An possible way would be to force the OptionParse.new block parse to fail
> if ARGV[1] == nil. How to do this properly in Ruby?
>
> I love Ruby so much! Thx all!
> az
>
>
> Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
> <http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
>
Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>