Let's say I have
some_value = 23
I use the Integer
's times
method to loop.
Inside the iteration, is there an easy way, without keeping a counter, to see what iteration the loop is currently in?
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. Parameter: The function takes the integer till which the numbers are returned.
Loops are a fundamental concept in any programming language. They allow us to execute a specific action continuously as long as a specified condition is true. Ruby also offers the concept of loops that can perform similar actions.
The each() is an inbuilt method in Ruby iterates over every element in the range. Parameters: The function accepts a block which specifies the way in which the elements are iterated. Return Value: It returns every elements in the range.
Yes, just have your block accept an argument:
some_value.times{ |index| puts index } #=> 0 #=> 1 #=> 2 #=> ...
or
some_value.times do |index| puts index end #=> 0 #=> 1 #=> 2 #=> ...
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