1
array =
[ {
        :keyword => "A", 
        :total_value => "10"
    },
    {
        :keyword => "B", 
        :total_value => "5"
    },
    {
        :keyword => "C", 
        :total_value => "15"
    },
    {
        :keyword => "B", 
        :total_value => "6"
    },
    {
        :keyword => "A", 
        :total_value => "50"
    },
    {
        :keyword => "D", 
        :total_value => "40"
    },
    {
        :keyword => "A", 
        :total_value => "30"
    }]

我正在尝试用相同的:keyword值合并散列。通过巩固,我的意思是结合:total_value。例如,合并后...

new_array =
[ {
        :keyword => "A", 
        :total_value => "90"
    },
    {
        :keyword => "B", 
        :total_value => "11"
    },
    {
        :keyword => "C", 
        :total_value => "15"
    },
    {
        :keyword => "D", 
        :total_value => "40"
    }]
4

2 回答 2

5

注入是你的朋友:

combined_keywords = array.inject(Hash.new(0)){|acc, oh| acc[oh[:keyword]] += oh[:total_value].to_i ; acc }

或者,each_with_object在这种情况下,该方法可能更具可读性:

combined_keywords = array.each_with_object(Hash.new(0)){|oh, newh| newh[oh[:keyword]] += oh[:total_value].to_i }

上述两种方法在功能上是等效的。

最后,如果您真的希望它采用哈希数组样式,这将使您到达那里:

combined_keywords.collect{|(k,v)| {:keyword => k,  :total_value => v}}
于 2013-04-23T16:57:01.797 回答
0

我认为它可能是这样的

new_array = {}
array.each do |hsh|
  new_array[hsh[:keyword]] ||= 0
  new_array[hsh[:keyword]] += hsh[:total_value].to_i
end
于 2013-04-23T16:48:56.710 回答