OptionParse with no arguments show banner

Israel picture Israel · Dec 16, 2013 · Viewed 7.5k times · Source

I'm using OptionParser with Ruby.

I other languages such as C, Python, etc., there are similar command-line parameters parsers and they often provide a way to show help message when no parameters are provided or parameters are wrong.

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: calc.rb [options]"

  opts.on("-l", "--length L", Integer, "Length") { |l| options[:length] = l }
  opts.on("-w", "--width W", Integer, "Width") { |w| options[:width] = w }

  opts.on_tail("-h", "--help", "Show this message") do
    puts opts
    exit
  end
end.parse!

Questions:

  1. Is there a way to set that by default show help message if no parameters were passed (ruby calc.rb)?
  2. What about if a required parameter is not given or is invalid? Suppose length is a REQUIRED parameter and user do not pass it or pass something wrong like -l FOO?

Answer

Малъ Скрылевъ picture Малъ Скрылевъ · Dec 16, 2013

Just add the -h key to the ARGV, when it is empty, so you may to do something like this:

require 'optparse'

ARGV << '-h' if ARGV.empty?

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: calc.rb [options]"

  opts.on("-l", "--length L", Integer, "Length") { |l| options[:length] = l }
  opts.on("-w", "--width W", Integer, "Width") { |w| options[:width] = w }

  opts.on_tail("-h", "--help", "Show this message") do
    puts opts
    exit
  end
end.parse!