新手问题 数组哈希累加

ane · 2018年11月14日 · 最后由 ruby_p 回复于 2018年11月16日 · 1943 次阅读
records =[{"delivery_income_num"=>62,
  "delivery_num"=>0,
  "income_fee"=>3,
  "pickup_alipay_pay_num"=>0,
  "pickup_wechat_pay_num"=>3,
  "box_num"=>0,
}]

    def sum_overview(records)
      delivery_num = 0.0
      income_fee = 0.0
      box_num = 0.0
      records.each do |record|
        delivery_num = delivery_num + record[:delivery_num]
        income_fee = income_fee + record[:income_fee]
        box_num = box_num + record[:box_num]
      end
      {delivery_num: delivery_num, income_fee: income_fee, delivery_rate: delivery_num/box_num}
    end

有个哈希数组,需要对数组里的每个哈希的 value 累加,有什么代码简洁而且还高效的方法 或者有没有类似处理功能的 gem 推荐

ane 关闭了讨论。 11月14日 19:19
ane 重新开启了讨论。 11月14日 19:20
elivery_income_num_count = records.map {|s| s['delivery_income_num']}.reduce(0, :+)
keys = %w[delivery_num income_fee box_num]
delivery_num, income_fee, box_num = 
  records.map{|h| h.values_at *keys}.transpose.map{|s| s.reduce 0, :+}
5 楼 已删除
[{a:1,b:2},{a:2,b:3}].map(&:to_a).transpose.map{|group| [group.first.first, group.map(&:last).inject(:+)]}.to_h
#=> {:a=>3, :b=>5}

(其实可读性一般般。

https://docs.ruby-lang.org/en/2.5.0/Hash.html#method-i-merge

h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.merge(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
h1.merge(h2){|key, oldval, newval| newval - oldval}
               #=> {"a"=>100, "b"=>54,  "c"=>300}
h1             #=> {"a"=>100, "b"=>200}
records.each_with_object({}) do |record, hash|
  record.each do |k, v|
    hash[k] ||= 0.0
    hash[k] += v
  end
end

h1 = {'a' =>1,'b' => 2} h2 = {'a' =>6, 'b' => 4} h1 = h1.merge(h2) {|k,v1,v2| v1 + v2}

需要 登录 后方可回复, 如果你还没有账号请 注册新账号