为什么在哈希中向数组追加值也会修改赋值给它的其他变量? [英] Why is append a value to an array in hash will also modify the other variable that have it assigned?
本文介绍了为什么在哈希中向数组追加值也会修改赋值给它的其他变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
样品的编号:
hash_of_array = {A:[]}
B = hash_of_array
C = hash_of_array
b [:a]<< 1
puts b#=> {a:[1]}
puts c#=> {a:[1]}
为什么两个变量在数组中都有1?我只将它附加在变量 b
上。
试过
- Ruby版本2.3.1,2.4.0
- Rbenv
解决方案
由于 b
的值和 c
是同一个对象(查看对象#
object_id
):
b.object_id = = c.object_id
#=>真
Sample code:
hash_of_array = { a: [] }
b = hash_of_array
c = hash_of_array
b[:a] << 1
puts b # => { a: [1] }
puts c # => { a: [1] }
Why do both variable have 1 in their array? I only appended it on variable b
.
Tried on
- Ruby Version 2.3.1, 2.4.0
- Rbenv
解决方案
Because value of b
and value of c
is the same object (check out Object#object_id
):
b.object_id == c.object_id
#=> true
这篇关于为什么在哈希中向数组追加值也会修改赋值给它的其他变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文