Ruby: loop with index?

Sometimes I use Ruby Enumerable#each_with_indexinstead Array#eachwhen I want to track an index. Is there a way, for example Kernel#loop_with_index, that I could use instead Kernel#loop?

+4
source share
3 answers

a loop without a block leads to an enumerator that has a method with_index(and each_with_indexif you prefer.)

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

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

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

But I would just use Kernel#loopand track the index myself, because it seems simpler.

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

So yes, I don’t think there is anything like that Kernel#loop_with_index.

+3
source

Ruby # Infinity 1.

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

Source: https://habr.com/ru/post/1536238/


All Articles