On Jan 28, 4:43=A0pm, Adam Prescott <mention... / gmail.com> wrote:
> [Note: =A0parts of this message were removed to make it a legal post.]
>
> On Fri, Jan 28, 2011 at 2:44 PM, Anurag Priyam <anurag08pri... / gmail.com>=
wrote:
>
> > >> foo =3D [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
> > >> groups =3D Hash.new{|h, k| h[k] =3D []}
> > >> foo.each{|i| groups[i] << i}
>
> > >> groups =A0 =A0 =3D> {1=3D>[1], 2=3D>[2, 2], 3=3D>[3, 3, 3], 4=3D>[4,=
 4, 4, 4]}
> > >> groups[3] =3D> [3, 3, 3]
>
> I think Rails provides this method for pre-1.8.7, but for 1.8.7 and highe=
r
> you can use group_by:
>
> >> (1..10).group_by { |n| n % 2 }
>
> =3D> {0=3D>[2, 4, 6, 8, 10], 1=3D>[1, 3, 5, 7, 9]}
>
> which is more easily generalised than the quoted code's approach, and eas=
ier
> to read, certainly. As an exercise, maybe try implementing your own
> Enumerable#group_by method; it's good for getting your head around how #e=
ach
> and mixins work, as well as yielding to blocks.

Many thanks!

what i finally did :

%w(category_1 category_2 category_3).map{|c| ls.select{|li|
li.category =3D=3D c}}

where ls are all the elements i need to group.. anyway, the native
rails group_by method is much better, i didnt know it exists!