From: Robert Klemme Date: 2010-01-07T00:20:13+09:00 Subject: Re: group in the array On 01/06/2010 03:56 PM, Ralf Mueller wrote: > Robert Klemme wrote: >> On 01/06/2010 09:45 AM, Kolya17 Kolya17 wrote: >>> Hi! >>> >>> I have a two-dimensional array Farr. >>> >>> Farr.each{ |i| print i} >>> >>> output: >>> ["200912-829", 9] >>> ["200912-893", 3] >>> ["200912-893", 5] >>> ["200912-829", 1] >>> ["200911-818", 6] >>> ["200911-893", 1] >>> ["200911-827", 2] >>> >>> I'm trying to get another two-dimensional array, which would be the >>> grouping of the first elements. >>> In SQL it would be so: >>> >>> select String, sum(Number) >>> from Farr >>> group by String >>> >>> and the resulting array would: >>> ["200912-829", 10] >>> ["200912-893", 8] >>> ["200911-818", 6] >>> ["200911-893", 1] >>> ["200911-827", 2] >>> >>> Help please. >>> I apologize for spelling, English is not my native. >> There is actually Array#group_by since 1.8.7: >> >> arr.group_by {|date,val| date}.each do |date, items| >> printf "%-20s %6d\n", date, items.inject(0) {|sum,x|sum+x}, "\n" >> end >> > Looks good, but I could not find it in the online documentation on > ruby-doc.org? (Array,Enumerable) That's weird. I found it immediately: group_by http://ruby-doc.org/core-1.8.7/classes/Enumerable.html#M001150 inject http://ruby-doc.org/core-1.8.7/classes/Enumerable.html#M001147 Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/