Sida Zhou
Sida Zhou

Reputation: 3705

How to modify an iterator while iterating over an array

I want to skip a loop x times according to a condition that is determined at runtime. How can I do this?

for i in (0..5)
  if i==0
    3.times {next} # i=i+3 also doesnt work
  end
  puts i
end

Expect to output

3
4
5

EDIT: To clarify, the question is both the condition (ie i==0) and skipping x times iteration are determined dynamically at runtime, more convoluted example:

condition = Array.new(rand(1..100)).map{|el| rand(1..10000)} #edge cases will bug out
condition.uniq!

for i in (0..10000)
  if condition.include? i
    rand(1..10).times {next} # will not work
  end
  puts i
end

Upvotes: 1

Views: 152

Answers (1)

Jerrÿ Chang
Jerrÿ Chang

Reputation: 105

simple method to skip by a defined multiple.

array_list = (0..5).to_a
# Use a separate enum object to hold index position
enum = array_list.each 
multiple = 3

array_list.each do |value|
  if value.zero?     
    multiple.times { enum.next }
  end   
  begin puts enum.next rescue StopIteration end
end

Upvotes: 4

Related Questions