Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate every two elements in ruby for loop

Tags:

ruby

How do you create a for loop like

for (int x=0; x<data.length; x+=2) 

in ruby? I want to iterate through an array but have my counter increment by two instead of one.

like image 384
Tsvi Tannin Avatar asked Aug 20 '13 15:08

Tsvi Tannin


People also ask

What does .each do in Ruby?

The each() is an inbuilt method in Ruby iterates over every element in the range. 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.

What is the simplest way to iterate through the items of an array Ruby?

The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array. It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.

How do you go through an array in Ruby?

Ruby each Method To iterate over an array in Ruby, use the . each method. It is preferred over a for loop as it is guaranteed to iterate through each element of an array.


2 Answers

If what you really want is to consume 2 items from an array at a time, check out each_slice.

[1,2,3,4,5,6,7,8,9].each_slice(2) do |a, b|
  puts "#{a}, #{b}"
end

# result
1, 2
3, 4
5, 6
7, 8
9,
like image 132
John Ledbetter Avatar answered Sep 19 '22 16:09

John Ledbetter


Ruby's step is your friend:

0.step(data.length, 2).to_a
=> [0, 2, 4, 6]

I'm using to_a to show what values this would return. In real life step is an enumerator, so we'd use it like:

data = [0, 1, 2, 3, 4, 5]
0.step(data.length, 2).each do |i|
  puts data[i]
end

Which outputs:

0
2
4
   <== a nil 

Notice that data contains six elements, so data.length returns 6, but an array is a zero-offset, so the last element would be element #5. We only get three values, plus a nil which would display as an empty line when printed, which would be element #6:

data[6]
=> nil

That's why we don't usually walk arrays and container using outside iterators in Ruby; It's too easy to fall off the end. Instead, use each and similar constructs, which always do the right thing.

To continue to use step and deal with the zero-offset for arrays and containers, you could use:

0.step(data.length - 1, 2)

but I'd still try working with each and other array iterators as a first choice, which @SergioTulentsev was giving as an example.

like image 29
the Tin Man Avatar answered Sep 19 '22 16:09

the Tin Man