each.with_index

13 views
Skip to first unread message

Avi

unread,
Jan 10, 2014, 7:02:58 AM1/10/14
to rubyonra...@googlegroups.com
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

Dave Aronson

unread,
Jan 10, 2014, 9:56:37 AM1/10/14
to rubyonrails-talk
On Fri, Jan 10, 2014 at 7:02 AM, Avi <aavinas...@gmail.com> wrote:

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

Take a look at the % (modulus) operator.

-Dave

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

Max

unread,
Jan 11, 2014, 1:37:04 PM1/11/14
to rubyonra...@googlegroups.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
Reply all
Reply to author
Forward
0 new messages