ruby – 如何在哈希中引用键的值
发布时间:2020-12-17 02:12:28 所属栏目:百科 来源:网络整理
导读:我希望能够引用Hash中的键,以便如果该键的值发生更改,那么引用它的任何内容都会发生变化 hash = {}hash[1] = "foo"hash[2] = hash[1]hash[1] = "bar"puts hash[2] # I want this to be "bar" 这可能吗?谢谢! 解决方法 这是不可能的.这是发生了什么: hash[
我希望能够引用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"} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |