gpt4 book ai didi

ruby - 没有参数的 OptionParse 显示横幅

转载 作者:数据小太阳 更新时间:2023-10-29 06:33:11 27 4
gpt4 key购买 nike

我在 Ruby 中使用 OptionParser

我的其他语言如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!

问题:

  1. 有没有办法设置在没有传递参数时默认显示 help 消息 (ruby calc.rb)?
  2. 如果必需参数未给出或无效怎么办?假设 length 是一个 REQUIRED 参数并且用户没有传递它或者传递了一些错误的东西比如 -l FOO?

最佳答案

只需将 -h 键添加到 ARGV 中,当它为空时,您可以这样做:

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!

关于ruby - 没有参数的 OptionParse 显示横幅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20604680/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com