2016-05-13 11 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 

をし、私はプログラムが出てHello World代わりに置くのですかどのように必要な引数INPUTせずに、このフラグを実行します:<main>': missing argument: -t (OptionParser::MissingArgument)

例:

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 

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]}" 
    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 
は、
関連する問題