2016-05-13 35 views
0

我有一個創建電子郵件,我想要做的是當給出-t標誌,並且沒有參數與標誌,默認的東西給一個程序給定沒有,相反,它輸出平時:<main>': missing argument: -t (OptionParser::MissingArgument)如何默認信息,如果是使用optparse

所以我的問題的存在,如果我有這樣的標誌:

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> 

回答

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 

我可以輸出提供的信息,或者有沒有提供任何信息,我可以輸出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 
相關問題