【问题标题】:Sum 2 hashes attributes with the same key对具有相同键的 2 个哈希属性求和
【发布时间】:2011-05-04 17:43:12
【问题描述】:

我有 2 个哈希,例如:

{'a' => 30, 'b' => 14}
{'a' => 4, 'b' => 23, 'c' => 7}

其中abc 是对象。如何将这些哈希的键相加以获得新的哈希,例如:

{'a' => 34, 'b' => 37, 'c' => 7}

【问题讨论】:

    标签: ruby hash attributes sum


    【解决方案1】:
    a_hash = {'a' => 30, 'b' => 14}
    b_hash = {'a' => 4, 'b' => 23, 'c' => 7}
    
    a_hash.merge(b_hash){ |k, a_value, b_value| a_value + b_value }
    => {"a"=>34, "b"=>37, "c"=>7}
    
    b_hash.merge(a_hash){ |k, b_value, a_value| a_value + b_value }
    => {"a"=>34, "b"=>37, "c"=>7}
    

    【讨论】:

    • 如何只添加特定的键?
    【解决方案2】:

    如果有人希望添加超过 2 个哈希,请使用此

    #sample array with any number of hashes
    sample_arr =  [{:a=>2, :b=>4, :c=>8, :d=>20, :e=>5},
    {:a=>1, :b=>2, :c=>4, :d=>10, :e=>5, :r=>7},
    {:a=>1, :b=>2, :c=>4, :d=>10},
    {:a=>2, :b=>4, :c=>8, :d=>20, :e=>5},
    {:a=>1, :b=>2, :c=>4, :d=>10, :e=>5, :r=>7},
    {:a=>1, :b=>2, :c=>4, :d=>10}]
    
    sample_arr.inject { |acc, next_obj| acc.merge(next_obj) { |key,arg1,arg2| arg1+arg2 } }
    # => {:a=>8, :b=>16, :c=>32, :d=>80, :e=>20, :r=>14} 
    

    如果是异构哈希(包含字符串和数字)。仅用于添加整数。

    @resultant_visit_hash = arr.inject { |acc, next_obj| acc.merge(next_obj) { |key,arg1,arg2| arg1+arg2 if (arg1.class == Integer && arg2.class == Integer) } } 
    

    代码是不言自明的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-03
      • 2014-04-23
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 2016-03-11
      相关资源
      最近更新 更多