Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over an array skipping every second element?

Tags:

ruby

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?

like image 576
pangpang Avatar asked Sep 05 '25 03:09

pangpang


2 Answers

You can specify .step size as an argument actually:

(0...arr.length).step(2) { |i| puts arr[i] }
like image 160
Rustam A. Gasanov Avatar answered Sep 08 '25 00:09

Rustam A. Gasanov


Another way is to use Array::each_slice:

 arr.each_slice(2) { |n| p n.first }
like image 22
xdazz Avatar answered Sep 07 '25 22:09

xdazz