我有一个创建电子邮件的程序,我想要做的是当-t
给定标志并且不给标志提供参数时,默认为某样东西,而是输出通常的代码:<main>': missing argument: -t (OptionParser::MissingArgument)
所以我的问题是,如果我有这个标志:
require 'optparse'
OPTIONS = {}
OptionParser.new do |opts|
opts.on('-t INPUT', '--type INPUT', 'Specify who to say hello to'){ |o| OPTIONS[:type] = o }
end.parse!
def say_hello
puts "Hello #{OPTIONS[:type]}"
end
case
when OPTIONS[:type]
say_hello
else
puts "Hello World"
end
并且我在没有必需参数的情况下运行此标志,INPUT
如何使程序输出Hello World
而不是:<main>': missing argument: -t (OptionParser::MissingArgument)
?
例子:
C:\Users\bin\ruby\test_folder>ruby opt.rb -t hello
Hello hello
C:\Users\bin\ruby\test_folder>ruby opt.rb -t
opt.rb:7:in `<main>': missing argument: -t (OptionParser::MissingArgument)
C:\Users\bin\ruby\test_folder>
我发现可以通过在方括号周围添加方括号INPUT
来提供输入示例的选项:
require 'optparse'
OPTIONS = {}
OptionParser.new do |opts|
opts.on('-t [INPUT]', '--type [INPUT]', 'Specify the type of email to be generated'){ |o| OPTIONS[:type] = o }
end.parse!
def say_hello
puts "Hello #{OPTIONS[:type]}"
end
case
when OPTIONS[:type]
say_hello
else
puts "Hello World"
end
输出:
C:\Users\bin\ruby\test_folder>ruby opt.rb -t
Hello World
C:\Users\bin\ruby\test_folder>ruby opt.rb -t hello
Hello hello
因此,如果我这样做:
require 'optparse'
OPTIONS = {}
OptionParser.new do |opts|
opts.on('-t [INPUT]', '--type [INPUT]', 'Specify the type of email to be generated'){ |o| OPTIONS[:type] = o }
end.parse!
def say_hello
puts "Hello #{OPTIONS[:type]}"
puts
puts OPTIONS[:type]
end
case
when OPTIONS[:type]
say_hello
else
puts "Hello World"
puts OPTIONS[:type] unless nil; puts "No value given"
end
我可以输出提供的信息,或者当没有信息提供时,我可以输出No value given
:
C:\Users\bin\ruby\test_folder>ruby opt.rb -t hello
Hello hello
hello
C:\Users\bin\ruby\test_folder>ruby opt.rb -t
Hello World
No value given
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句