如何使用optparse在未给定信息时默认为某些信息

3
我有一个创建邮件的程序,我想做的是当给出-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>
1个回答

0

我发现通过在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

我可以输出提供的信息,或者当没有提供信息时,我可以输出未提供数值
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接