2016-07-05 4 views
0

flags引数を持つようにoptparseは使用する方法私は私が更新してるのツールを持っていると引数は例えば別の引数を必要としておく必要があります。どのように別の引数を必要と

require 'optparse' 

OPTIONS = {} 

OptionParser.new do |opts| 
    opts.on('-t', '--type INPUT', String, 'Verify a type'){ |o| OPTIONS[:type] = o } 
end.parse! 

def help_page 
    puts 'ruby test.rb -t dev' 
end 

def gather_type 
    case OPTIONS[:type] 
    when /dev/ 
    unlock(OPTIONS[:type]) 
    else 
    help_page 
    end 
end 

def unlock(type) 
    if type == 'unlock' #Find out what type by passing argument another argument 
    puts 'Unlock account' 
    else 
    puts 'Reset account' 
    end 
end 

def start 
    case 
    when OPTIONS[:type] 
    gather_type 
    else 
    help_page 
    end 
end 

start 

これはあなたが得る実行されると次

C:\Users\bin\ruby>ruby test.rb -t dev=unlock 
Reset account 
C:\Users\bin\ruby>ruby test.rb -t dev=reset 
Reset account 

は、今ではすべてが順調とダンディですが、私は何をしたいdev一部に引数を与えると、それはロック解除ですか、それはリセットかどうかを決定するためにそこから行くです:

ruby test.rb -t dev=unlockまたは私はunlock(type)方法は、flags引数と出力正しい情報に与えられたものを引数を決定したいその後ruby test.rb -t dev=reset

、私は引数がいたかどうかを判断しようとして行くことができますどのように

C:\Users\bin\ruby>ruby test.rb -t dev=unlock 
Unlock account 

C:\Users\bin\ruby>ruby test.rb -t dev=reset 
Reset account 

旗の議論に与えられた?

答えて

0

私はあなたが括弧内のオプションを置けばあなたは私が求めているものを得ることができることを考え出し:

require 'optparse' 

OPTIONS = {} 

OptionParser.new do |opts| 
    opts.on('-t', '--type INPUT[=INPUT]', String, 'Verify a type'){ |o| OPTIONS[:type] = o } 
end.parse! 

def help_page 
    puts 'ruby test.rb -t dev' 
end 

def gather_type 
    case OPTIONS[:type] 
    when /dev/ 
    unlock(OPTIONS[:type]) 
    else 
    help_page 
    end 
end 

def unlock(type) 
    if type =~ /unlock/ #Find out what type by passing argument another argument 
    puts 'Unlock account' 
    elsif type =~ /reset/ 
    puts 'Reset account' 
    else 
    puts 'No flag given defaulting to unlock' 
    end 
end 

def start 
    case 
    when OPTIONS[:type] 
    gather_type 
    else 
    help_page 
    end 
end 

start 


C:\Users\bin\ruby>ruby test.rb -t dev 
No flag given defaulting to unlock 

C:\Users\bin\ruby>ruby test.rb -t dev=unlock 
Unlock account 

C:\Users\bin\ruby>ruby test.rb -t dev=reset 
Reset account 
関連する問題