Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Ruby version of for-loop similar to the one on Java/C++?

Is there a Ruby version of for-loop similar to the one in Java/C(++)?

In Java:

for (int i=0; i<1000; i++) {
    // do stuff
}

The reason is because I need to do different operations based on the index of the iteration. Looks like Ruby only has a for-each loop?

Am I correct?

like image 757
ryanprayogo Avatar asked Dec 09 '09 05:12

ryanprayogo


People also ask

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 is .each in Ruby?

The each() is an inbuilt method in Ruby iterates over every element in the range. Syntax: range1.each(|el| block) 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.

Is there an equivalent of continue in Ruby?

The next statement in Ruby is equivalent to continue statement in other languages. Syntax: next.

How do you break a loop in Ruby?

In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.


1 Answers

Yes you can use each_with_index

collection = ["element1", "element2"]
collection.each_with_index {|item,index| puts item; puts index}

the 'index' variable gives you the element index during each iteration

like image 121
nas Avatar answered Sep 28 '22 07:09

nas