Array grouping methods with index

365 views
Skip to first unread message

Juanjo Bazan

unread,
May 14, 2011, 9:44:44 AM5/14/11
to Ruby on Rails: Core
I've found useful to have a port of the Array#each_with_index
functionality to the already existent grouping methods (in_groups_of,
in_groups). That way we add the ability to iterate over an array in
groups and having an index for each group.

In case you think it's interesting I've created a couple of methods:
Array#with_index_in_groups_of / with_index_in_groups and sent a pull
request here: https://github.com/rails/rails/pull/556

Cheers!,
Juanjo.

Aaron Patterson

unread,
May 14, 2011, 2:38:23 PM5/14/11
to rubyonra...@googlegroups.com

Can't you just use the enumerators that are built in to Array itself?
For example:

irb(main):006:0> x = %w(1 2 3 4 5 6 7)
=> ["1", "2", "3", "4", "5", "6", "7"]
irb(main):007:0> x.each_slice(3).each_with_index { |(a, b, c), i|
p [i, [a, b, c]] }
[0, ["1", "2", "3"]]
[1, ["4", "5", "6"]]
[2, ["7", nil, nil]]
=> nil
irb(main):008:0>

--
Aaron Patterson
http://tenderlovemaking.com/

Juanjo Bazán

unread,
May 14, 2011, 5:29:22 PM5/14/11
to rubyonra...@googlegroups.com
> Can't you just use the enumerators that are built in to Array itself?
> For example:
>
>    irb(main):006:0> x = %w(1 2 3 4 5 6 7)
>    => ["1", "2", "3", "4", "5", "6", "7"]
>    irb(main):007:0> x.each_slice(3).each_with_index { |(a, b, c), i|
>      p [i, [a, b, c]] }
>    [0, ["1", "2", "3"]]
>    [1, ["4", "5", "6"]]
>    [2, ["7", nil, nil]]
>    => nil
>    irb(main):008:0>

Sure, actually both methods are just syntactic sugar over the grouping methods:

with_index_in_groups_of = in_groups_of + each_with_index
with_index_in_groups = in_groups + each_with_index

J.

Reply all
Reply to author
Forward
0 new messages