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
?
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.
“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.
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.
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.
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}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With