From: Adam Prescott Date: 2011-01-29T00:43:37+09:00 Subject: Re: Group elements by category --90e6ba61533afc625b049ae9d90b Content-Type: text/plain; charset=UTF-8 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. --90e6ba61533afc625b049ae9d90b--