, , :
items.inject([]) { |arr, el| arr[el[0]] = [el[0], (arr[el[0]] || [_, 0])[1] + el[1]]; arr }.compact
?
items.inject([]) { |arr, el|
arr[el[0]] = [el[0], (arr[el[0]] || [_, 0])[1] + el[1]]
arr
}.compact
#inject items. el items arr. , [60, 3] 60 ( ) [60, 3].
arr: [el[0], (arr[el[0]] || [_, 0])[1] + el[1]]. , , , 0.
. compact .
, .
, , , ( ) :
require 'benchmark'
items = [[60, 3], [60, 3], [276, 2], [276, 2], [48, 2], [207, 2], [46, 2],
[60, 2], [280, 2], [207, 1], [48, 1], [112, 1], [60, 1], [207, 1], [112, 1],
[276, 1], [48, 1], [276, 1], [48, 1], [276, 1], [276, 1], [278, 1], [46, 1],
[48, 1], [279, 1], [207, 1]]
Benchmark.bmbm do |x|
x.report(:long) { items.group_by {|i| i[0]}.map{|key, value| [key,value.inject(0){|sum, x| sum + x[1]}]} }
x.report(:randym) { items.reduce(Hash.new { |hash, key| hash[key] = 0 }) { |memo, item| memo[item[0]] = memo[item[0]] + item[1]; memo }.to_a }
x.report(:eric) { items.inject([]) { |arr, el| arr[el[0]] = [el[0], (arr[el[0]] || [0, 0])[1] + el[1]]; arr }.compact }
end
:
Rehearsal ------------------------------------------
long 0.000000 0.000000 0.000000 ( 0.000016)
randym 0.000000 0.000000 0.000000 ( 0.000014)
eric 0.000000 0.000000 0.000000 ( 0.000011)
--------------------------------- total: 0.000000sec
user system total real
long 0.000000 0.000000 0.000000 ( 0.000013)
randym 0.000000 0.000000 0.000000 ( 0.000011)
eric 0.000000 0.000000 0.000000 ( 0.000008)
Rehearsal ------------------------------------------
long 0.000000 0.000000 0.000000 ( 0.000024)
randym 0.000000 0.000000 0.000000 ( 0.000014)
eric 0.000000 0.000000 0.000000 ( 0.000011)
--------------------------------- total: 0.000000sec
user system total real
long 0.000000 0.000000 0.000000 ( 0.000013)
randym 0.000000 0.000000 0.000000 ( 0.000011)
eric 0.000000 0.000000 0.000000 ( 0.000014)
. Long Randym .
, : , , , : -)