ma11hew28
ma11hew28

Reputation: 126329

Ruby: loop with index?

Sometimes, I use Ruby's Enumerable#each_with_index instead of Array#each when I want to keep track of the index. Is there a method like Kernel#loop_with_index I could use instead of Kernel#loop?

Upvotes: 13

Views: 12763

Answers (3)

steenslag
steenslag

Reputation: 80065

In recent Ruby versions, Numeric#step has a default limit of Infinity and a step-size of 1.

0.step{|i| puts i ; break if i>100 }

Upvotes: 4

steenslag
steenslag

Reputation: 80065

loop without a block results in an Enumerator, which has a with_index method (and a each_with_index if you prefer that.)

loop.with_index{|_, i| puts i; break if i>100}

Upvotes: 25

ma11hew28
ma11hew28

Reputation: 126329

You could use Fixnum#upto with Float::INFINITY.

0.upto(Float::INFINITY) do |i|
  puts "index: #{i}"
end

But, I'd probably just use Kernel#loop and keep track of the index myself because that seems simpler.

i = 0
loop do
  puts "index: #{i}"
  i += 1
end

So, yeah, I don't think there's anything like Kernel#loop_with_index.

Upvotes: 3

Related Questions