How to iterate over an array skipping every second element?

How do I 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 do I do it?

+3


source to share


6 answers


You can specify the size as an argument .step

:



(0...arr.length).step(2) { |i| puts arr[i] }

      

+11


source


Another way is to use Array :: each_slice :



 arr.each_slice(2) { |n| p n.first }

      

+10


source


(0...arr.length).step(2) do |n|
end

      

OR

for i in (0...arr.length).step(2) do
    puts arr[i]
end

      

Step

is used to increment the value of n and this loop will continue until arr.length

+2


source


You can also try:

> arr = Array('a'..'z')
#=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] 
> arr.select.each_with_index{|k,i| k if i.even?} 
#=> ["a", "c", "e", "g", "i", "k", "m", "o", "q", "s", "u", "w", "y"]

      

I like step

, and slice

a method that has already been said, so it's just a different approach .;)

+2


source


a million and one way to solve array problems. If you don't really need a loop this will pull the values ​​easily

a = (0..20).to_a
a.values_at(*(0..a.size).step(2))
#=> => [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

      

0


source


Using a while loop can be done like this: -

#!/usr/bin/ruby
arr=[1,2,3,4,5,6]  
i=0
begin
    puts arr.at(i*2)
i += 1
puts "value of i is #{i}" 
end while (i*2) < arr.length

      

0


source







All Articles