Difference between update(other_hash) and merge(ot

2020-08-12 18:48发布

问题:

Update Code:

irb(main):001:0> h1 = { "a" => 100, "b" => 200 }
=> {"a"=>100, "b"=>200}
irb(main):002:0> h2 = { "b" => 254, "c" => 300 }
=> {"b"=>254, "c"=>300}
irb(main):003:0> h1.update(h2)
=> {"a"=>100, "b"=>254, "c"=>300}

Merge Code:

irb(main):001:0> h1 = { "a" => 100, "b" => 200 }
=> {"a"=>100, "b"=>200}
irb(main):002:0> h2 = { "b" => 254, "c" => 300 }
=> {"b"=>254, "c"=>300}
irb(main):003:0> h1.merge(h2)
=> {"a"=>100, "b"=>254, "c"=>300}
irb(main):004:0>

I ran the above merge and update method on the same hash. But got the same output. So here my question is: are update and merge works with same logic? if not same then how the output came same for those?

回答1:

Are update and merge works with same logic?

No, they are not the same. update is an alias for merge!, which is the in-place variant of merge.

if not same then how the output came same for those?

Because in both cases you are using the return value of the call, however, the value of h1 is different in each case:

h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.update(h2)
h1  #=> { "a" => 100, "b" => 254, "c" => 300 }

h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.merge(h2)
h1  #=> { "a" => 100, "b" => 200 }


回答2:

Hash#update is an alias for Hash#merge! http://ruby-doc.org/core-1.9.3/Hash.html#method-i-update



回答3:

Hash#update is alias to Hash#merge!

The difference between Hash#merge and Hash#update is Hash#update updates keys/values in-place, whereas Hash#merge returns updated hash without touching the calling instance.



回答4:

h1.update(h2) - updates h1 instance - returns updated h1; h1.merge(h2) - leaves h1 and creates updated copy - returns a updated copy of h1 (h3 I could call it)



标签: ruby