How to write this type of for loop in ruby?
for(i = 0; i < arr.length; i = i+2) {
}
I know how to write it if step is 1, but if step > 1, how to make it?
You can specify .step
size as an argument actually:
(0...arr.length).step(2) { |i| puts arr[i] }
Another way is to use Array::each_slice:
arr.each_slice(2) { |n| p n.first }
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