How do I do this type of for loop in Ruby?
for(int i=0; i<array.length; i++) { }
The simplest way to create a loop in Ruby is using the loop method. loop takes a block, which is denoted by { ... } or do ... end . A loop will execute any code within the block (again, that's just between the {} or do ...
Syntax of a For LoopThe initialization statement describes the starting point of the loop, where the loop variable is initialized with a starting value. A loop variable or counter is simply a variable that controls the flow of the loop. The test expression is the condition until when the loop is repeated.
A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number.
array.each do |element| element.do_stuff end
or
for element in array do element.do_stuff end
If you need index, you can use this:
array.each_with_index do |element,index| element.do_stuff(index) end
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