100, "b" => 200 } => {"a"=>100, "b"=>200} irb(main):002:0> h2 =-6ren">
gpt4 book ai didi

ruby - update(other_hash) 和 merge(other_hash) 的区别

转载 作者:数据小太阳 更新时间:2023-10-29 06:40:31 26 4
gpt4 key购买 nike

更新代码:

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}

合并代码:

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>

我在同一个 hash 上运行了上面的 mergeupdate 方法。但是得到了相同的输出。所以我的问题是:updatemerge 是否使用相同的逻辑?如果不相同,那么这些输出如何相同?

最佳答案

Are update and merge works with same logic?

不,它们不一样。 update is an alias for merge! ,这是 merge 的就地变体。

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

因为在这两种情况下您都使用调用的返回值,但是,h1 的值在每种情况下都不同:

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 }

关于ruby - update(other_hash) 和 merge(other_hash) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14307034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com