From: William James Date: 2007-10-20T10:05:03+09:00 Subject: Re: What's the ruby way of grouping elements of an array? On Oct 19, 2:01 pm, Sam Kong wrote: > Hi, > > I thought this would be a common need but I couldn't find a method. > > Let's say I have an array of objects. > I want to group the elements by a property of objects. > > people.group_by do |person| > person.age > end > > The above method should return an array of arrays grouped by age. > > What's the ruby way for this case? > I think I can implement it but I am sure that a good way already exists. > > Thanks. > > Sam It's pretty simple. class Array def group_by h = Hash.new{ [] } each{|x| h[ yield( x ) ] += [ x ] } h.values end end p %w(a little while ago I heard the tittering of a mouse). group_by{|s| s.size }