我需要合并几个哈希。我的意思是:
a = {:x => 72, :y => 2}
b = {:x => 34, :y => 24}
c = a.deep_merge!(b)
,c
是{:x => 106, :y => 26}
。
Crystal中的功能是否像Ruby中的deep_merge
一样?
编辑:实际的hash
是更多复杂
{"request" => {"duration" => 15100012.0, "total" => 252562.0, "per_second" => 16725.0, "bytes" => 43440664.0}, "error" => {"socket" => 0.0, "read" => 25.0, "write" => 0.0, "http" => 0.0, "timeout" => 0.0}, "latency" => {"minimum" => 234.0, "maximum" => 219466.0, "average" => 7640.0, "deviation" => 12940.0}, "percentile" => {"fifty" => 2732.0, "ninety" => 20335.0, "ninety_nine" => 65824.0, "ninety_nine_ninety" => 199536.0}}
实际上,它是json
转换为hash
的{{1}}
我的最终目标是在循环中添加一个由该哈希值(添加的值)组成的新哈希值
答案 0 :(得分:4)
您所描述的不是深度合并(递归操作),而是自定义合并策略。
可以通过以下方式调用Hash#merge
来解决此问题:
a = {:x => 72, :y => 2}
b = {:x => 34, :y => 24}
c = a.merge(b) { |_, v1, v2| v1 + v2 }
pp c # => {:x => 106, :y => 26}