Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know what iteration I'm in when using the Integer.times method?

Tags:

loops

ruby

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?

like image 925
EarlyPoster Avatar asked Apr 05 '10 15:04

EarlyPoster


People also ask

How do you use the time method 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. Parameter: The function takes the integer till which the numbers are returned.

Can you do a for loop in Ruby?

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.

What does each do in Ruby?

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.


1 Answers

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 #=> ... 
like image 86
Ken Avatar answered Sep 18 '22 15:09

Ken