将哈希值与相同的符号值组合在一起

时间:2013-04-23 16:40:41

标签: ruby-on-rails ruby arrays

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"
    }]

2 个答案:

答案 0 :(得分:5)

inject是你的朋友:

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}}

答案 1 :(得分:0)

我认为它可能是这样的

new_array = {}
array.each do |hsh|
  new_array[hsh[:keyword]] ||= 0
  new_array[hsh[:keyword]] += hsh[:total_value].to_i
end