In this code i want to iterate my array according to index value which is provided by code like one time i want to iterate and get output of ARGV[1] second time ARGV[3].
suppose
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
Instead of reinventing the wheel again, why don’t you use an option parser library to parse your program arguments.
For example with
OptionParseryour life would be much easier.In this particular problem, incrementing the
xvariable by one won’t help you, because in the next iterationeach_with_indexwill pass the next integer again. So, you should create your own loop: