没有参数的OptionParse显示横幅

Isr*_*ael 18 ruby optionparser

我正在使用OptionParserRuby.

我有其他语言,如C,Python等,有类似的命令行参数解析器,它们通常提供一种在没有提供参数或参数错误时显示帮助消息的方法.

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!
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 有没有办法设置默认显示help消息如果没有传递参数(ruby calc.rb)?
  2. 如果没有给出或无效的必要参数怎么办?假设length是一个REQUIRED参数,用户不传递它或传递错误,如-l FOO

Мал*_*евъ 35

你可能会做这样的事情:

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!
Run Code Online (Sandbox Code Playgroud)