哈希合并行为

发布于 2025-01-02 20:56:59 字数 204 浏览 4 评论 0原文

这种行为正确吗?我正在运行如下代码:

@a_hash = {:a => 1}
x = @a_hash
x.merge!({:b => 2})

最后,x 的值已按预期更改,但 @a_hash 的值也已更改。我得到了 {:a =>; 1、:b => 2} 作为它们两者的值。这是 Ruby 中的正常行为吗?

Is this behavior correct? I'm running some code like the following:

@a_hash = {:a => 1}
x = @a_hash
x.merge!({:b => 2})

At the end of all that, x's value has been changed as expected but so has the value for @a_hash. I'm getting {:a => 1, :b => 2} as the value for both of them. Is this normal behavior in Ruby?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

榕城若虚 2025-01-09 20:56:59

是的,实例变量 @a_hash 和局部变量 x 存储对同一 Hash 实例的引用,并且当您更改时在此实例中(使用 mutator 方法 merge! 就地更改对象),这些变量将被评估为相同的值。

您可能想要使用 merge 方法来创建对象的副本并且不更改原始对象:

@a_hash = {:a => 1}
x = @a_hash
y = x.merge({:b => 2})
# y => {:a => 1, :b => 2}
# x and @a_hash => {:a => 1}

Yes, instance variable @a_hash and local variable x store the reference to the same Hash instance and when you change this instance (using mutator method merge! that change object in place), these variables will be evaluated to the same value.

You may want to use merge method that create a copy of the object and don't change original one:

@a_hash = {:a => 1}
x = @a_hash
y = x.merge({:b => 2})
# y => {:a => 1, :b => 2}
# x and @a_hash => {:a => 1}
执笔绘流年 2025-01-09 20:56:59

@a_hash 是 x 的链接。所以如果你不想改变@a_hash,你应该这样做:

@a_hash = {:a => 1}
x = @a_hash.clone
x.merge!({:b => 2})

@a_hash is link to x. So if You want @a_hash not changed, you should do like this:

@a_hash = {:a => 1}
x = @a_hash.clone
x.merge!({:b => 2})
套路撩心 2025-01-09 20:56:59

是的,这是 ruby​​(以及大多数其他语言)中的正常行为。 x@a_hash 都是对同一对象的引用。通过调用merge!,您可以更改该对象,并且通过引用它的所有变量都可以看到该更改。

如果您不希望出现这种行为,则不应使用变异方法(即使用 x = x.merge(...) 代替)或在变异之前复制对象(即 x = @a_hash.dup)。

Yes, that's normal behavior in ruby (and most other languages). Both x and @a_hash are references to the same object. By calling merge! you change that object and that change in visible through all variables that refer to it.

If you don't want that behavior, you should either not use mutating methods (i.e. use x = x.merge(...) instead) or copy the object before you mutate it (i.e. x = @a_hash.dup).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文