2014-03-12 68 views
4

我有找到的所有事件一週一個ActiveRecord方法哈希, myevents.map { |x| x.start_date.day => [x.title]} (開始日期是該日期時間字段,標題是一個字符串) 這給了我哈希值的數組;Rails的Ruby的陣列通過鍵合併平均值

[{11=>["40"]}, {11=>["0"]}, {11=>["0"]}, {11=>[""]}, 
    {11=>["0"]}, {11=>["0"]}, {11=>["33"]}, {12=>["9"]}, 
    {11=>["34"]}, {11=>["29"]}, {11=>["8"]}, {11=>["31"]}, 
    {11=>["40"]}, {11=>["34"]}] 

我想映射的值,所以我得到一個數組,看起來像;

[ {11=>[ average of values that occur on the 11th]}, 
    {12=>[average of values that occur on the 12th]} ] 

但我不太清楚如何得到它。

回答

7

我會用group_by,injectmap

ar = [ 
     {11=>["40"]}, {11=>["0"]}, {11=>["0"]}, {11=>[""]}, 
     {11=>["0"]}, {11=>["0"]}, {11=>["33"]}, {12=>["9"]}, 
     {11=>["34"]}, {11=>["29"]}, {11=>["8"]}, {11=>["31"]}, 
     {11=>["40"]}, {11=>["34"]} 
    ] 

# first grouping the inner hash keys like on 11,12,etc. In each iteration, 
# {11=>["40"]}, {11=>["0"]} are being passed to the block of `group_by`. Now 
# `h.keys.first` gives 11 from `{11=>["40"]}` and 11 from `{11=>["0"]}` likewise. 
ary = ar.group_by { |h| h.keys.first }.map do |k,v| 
    { k => v.map { |h| h[k][0].to_i }.inject(:+)/v.size } 
end 

ary # => [{11=>19}, {12=>9}] 
+0

是什麼 '第一' 做 'h.keys.first'? –

+0

@raphael_turtle首先做'p ar.group_by {| h | h.keys.first}',看看下一個'map'模塊正在做什麼。 –

+0

感謝您的解釋! –

0

另一種方法: -

array = [ 
     {11=>["40"]}, {11=>["0"]}, {11=>["0"]}, {11=>[""]}, 
     {11=>["0"]}, {11=>["0"]}, {11=>["33"]}, {12=>["9"]}, 
     {11=>["34"]}, {11=>["29"]}, {11=>["8"]}, {11=>["31"]}, 
     {11=>["40"]}, {11=>["34"]} 
    ] 

    array.each_with_object({}) { |hObj, newHash| hObj.each { |k,v| 
     (newHash[k] ||= []) << v.first.to_i } }.collect{|k,v| 
     {k => (v.inject(:+))/v.size}} 

=> [{11=>19}, {12=>9}]