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.
>   
Hi again,
sort_by might be to simple for you, because of the sum. I tried this:

irb(main):039:0> a = [["200912-829", 10],["200912-893", 
8],["200911-818", 6],["200912-893", 5]]
=> [["200912-829", 10], ["200912-893", 8], ["200911-818", 6], 
["200912-893", 5]]
irb(main):040:0> aH = {}
=> {}
irb(main):041:0> a.each {|k,v| aH[k] = 0 if aH[k].nil?; aH[k] += v}
=> [["200912-829", 10], ["200912-893", 8], ["200911-818", 6], 
["200912-893", 5]]
irb(main):042:0> aH.sort
=> [["200911-818", 6], ["200912-829", 10], ["200912-893", 13]]

hth
ralf