gpt4 book ai didi

ruby - 如何引用哈希中键的值

转载 作者:数据小太阳 更新时间:2023-10-29 07:36:49 25 4
gpt4 key购买 nike

我希望能够引用 Hash 中的键,这样如果该键的值发生变化,那么引用它的任何内容也会发生变化

hash = {}

hash[1] = "foo"
hash[2] = hash[1]

hash[1] = "bar"

puts hash[2] # I want this to be "bar"

这可能吗?谢谢!

最佳答案

这是不可能的。这是正在发生的事情:

hash[1] = "foo"   # hash[1] is now a reference to the object "foo".
hash[2] = hash[1] # hash[2] is now a reference to the object "foo" as well,
# since it is what hash[1] is a reference to.
hash[1] = "bar" # hash[1] is now a reference to the object "bar"

请注意,分配 hash[1] 不会更改它引用的对象,而只是更改它引用的对象。

在 Ruby 中(与许多高级语言一样)您没有指针,也没有明确的操作引用的能力。

但是,有一些方法是可变的,在 String 上,一个这样的例子是 upcase!。在此示例中,我们可以看到此方法修改了被引用的实际对象而没有分配新对象(因此引用保持不变):

hash[1] = "foo"   #=> "foo"
hash[2] = hash[1] #=> "foo"
hash[2].upcase! #=> "FOO"
hash # => {1=>"FOO", 2=>"FOO"}

关于ruby - 如何引用哈希中键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8379814/

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