Reputation: 173
I need to merge several hashes. I mean having:
a = {:x => 72, :y => 2}
b = {:x => 34, :y => 24}
c = a.deep_merge!(b)
and c
is {:x => 106, :y => 26}
.
Is there a feature in Crystal like deep_merge
in Ruby?
EDIT : The real hash
is more complex
{"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}}
in fact it's a json
transformed in a hash
with PullParser
my final goal is to add create a new hash composed by values (added) from this hash on a loop
Upvotes: 1
Views: 175
Reputation: 639
What you are describing is not a deep merge (a recursive operation), but just a custom merge strategy.
It can be solved by calling Hash#merge
with a block:
a = {:x => 72, :y => 2}
b = {:x => 34, :y => 24}
c = a.merge(b) { |_, v1, v2| v1 + v2 }
pp c # => {:x => 106, :y => 26}
Upvotes: 4