Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: loop with index?

Tags:

loops

ruby

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?

like image 431
ma11hew28 Avatar asked Apr 12 '14 14:04

ma11hew28


People also ask

What does each with index do Ruby?

The each_with_index function in Ruby is used to Iterate over the object with its index and returns value of the given object. Here, A is the initialised object. Parameters: This function does not accept any parameters. Returns: the value of the given object.

Is there a for loop in Ruby?

“for” loop has similar functionality as while loop but with different syntax. for loop is preferred when the number of times loop statements are to be executed is known beforehand. It iterates over a specific range of numbers.

What does .times do in Ruby?

The times function in Ruby returns all the numbers from 0 to one less than the number itself. It iterates the given block, passing in increasing values from 0 up to the limit. If no block is given, an Enumerator is returned instead.

What does index mean in Ruby?

index is a String class method in Ruby which is used to returns the index of the first occurrence of the given substring or pattern (regexp) in the given string. It specifies the position in the string to begin the search if the second parameter is present. It will return nil if not found.


2 Answers

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}
like image 73
steenslag Avatar answered Sep 24 '22 10:09

steenslag


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.

like image 39
ma11hew28 Avatar answered Sep 25 '22 10:09

ma11hew28