From: Sergi Villanueva Date: 2011-02-02T17:35:41+09:00 Subject: Re: Group elements by category On Jan 28, 4:43 pm, Adam Prescott wrote: > [Note:  parts of this message were removed to make it a legal post.] > > On Fri, Jan 28, 2011 at 2:44 PM, Anurag Priyam wrote: > > > >> foo = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] > > >> groups = Hash.new{|h, k| h[k] = []} > > >> foo.each{|i| groups[i] << i} > > > >> groups     => {1=>[1], 2=>[2, 2], 3=>[3, 3, 3], 4=>[4, 4, 4, 4]} > > >> groups[3] => [3, 3, 3] > > I think Rails provides this method for pre-1.8.7, but for 1.8.7 and higher > you can use group_by: > > >> (1..10).group_by { |n| n % 2 } > > => {0=>[2, 4, 6, 8, 10], 1=>[1, 3, 5, 7, 9]} > > which is more easily generalised than the quoted code's approach, and easier > to read, certainly. As an exercise, maybe try implementing your own > Enumerable#group_by method; it's good for getting your head around how #each > 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 == 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!