[英]ruby array each_with_index
在這段代碼中,我想根據代碼提供的索引值來迭代數組,就像我一次要迭代並第二次獲得ARGV [1]的輸出一樣。
假設
ARGV = ["-f","abc","-x","-p","wer"]
#!/usr/bin/env ruby
@lenght = ARGV.length
@factory_config_xml = ""
@num = 0
if @lenght != 0
ARGV.each_with_index do |a , x|
@num = @num + 1
b = ARGV[@num]
if ((a == "-f") && !(b.match "-") )
@factory_config_xml = b
x += 1
@num = @num + 1
elsif ((a == "-x") && !(b.match "-") )
@factory_config_xml = b
x += 1
@num = @num + 1
elsif ((a == "-p") && !(b.match "-") )
@factory_config_xml = b
x += 1
@num = @num + 1
end
end
end
puts @factory_config_xml
與其重新發明輪子,不為什么不使用選項解析器庫來解析程序參數。
例如,使用OptionParser
您的生活會容易得多。
在這個特殊的問題中,將x
變量加1不會幫助您,因為在下一次迭代中, each_with_index
將再次傳遞下一個整數。 因此,您應該創建自己的循環:
i = 0
while (i < ARGV.length) do
# do your stuff with the incrementing but take care to increment in each loop
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.