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?
“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 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.
The next statement in Ruby is equivalent to continue statement in other languages. Syntax: next.
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.
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
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