2014-04-28 47 views
0

請看看這個簡單的代碼,名爲foo.rb:如何迭代Ruby GetoptLong對象兩次?

require('getoptlong') 
opts = GetoptLong.new( [ '--ies', GetoptLong::OPTIONAL_ARGUMENT ]) 
opts.each do | opt, arg | 
    if(opt == '--ies') 
    puts arg 
    end 
end 
opts.each do | opt, arg | 
    if(opt == '--ies') 
    puts arg 
    end 
end 

我想到,如果我在LINUX輸入:

foo.rb --ies=bar 

我會得到:

bar 
bar 

然而,我只得到1行:

bar 

爲什麼我不能通過GetoptLong實例迭代兩次? 謝謝,

+0

我建議[OptionParser(http://www.ruby-doc.org/stdlib-2.1.1/libdoc/optparse/rdoc/index。 HTML)。使用起來更容易。 –

回答

0

該實現不允許它。 GetoptLong#each循環調用GetoptLong#get_option,直到它返回nil,即「處理完成」。一旦完成,它總是返回nil,因此不能再次處理。

您可以創建一個數組:

opts_array = [] 
opts.each { |o, a| opts_array << [o, a] } 

opts_array.each do |opt, arg| 
    # ... 
end 
opts_array.each do |opt, arg| 
    # ... 
end