2016-07-05 57 views
0

我有一个工具,我更新,需要有一个参数需要另一种说法,例如:当这个运行你如何使用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 OR ruby test.rb -t dev=reset

后,我希望unlock(type)方法来确定给予了flags参数和输出正确的信息是什么参数,所以

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 
相关问题