Each.with_index

Hello,

I have an array :-
a = [1, 2, 3, 4, 5]

I have 13 objects with sequence. I want to assign a’s value to these
objects which will be repeated.
so after every 5 objects, these a’s value will be assigned & will be
repeated.

a.each.with_index do |col, col_index|
Some code here.
// How should I again assign the col_index to ‘0’ again, so that I
can
repeat those values & save values to the objects?
end

I am able to assign first 5 objects.

Thanks,
Avinash

On Fri, Jan 10, 2014 at 7:02 AM, Avi [email protected] wrote:

// How should I again assign the col_index to '0' again,

Take a look at the % (modulus) operator.

-Dave


Dave A., the T. Rex of Codosaurus LLC (codosaur.us),
freelance software developer, and creator of these sites:
PullRequestRoulette.com, blog.codosaur.us, & Dare2XL.com.

As Dave answered, modulus is your answer -

a.each_with_index do |obj, idx|
if (idx % 5 == 0)
# this is your starting point for each group of 5

end

do other stuff here…

end