任何人都可以向我解释一下:
irb(main):001:0> a = Array.new(3, [])
=> [[], [], []]
irb(main):001:0> b = [[], [], []]
=> [[], [], []]
irb(main):003:0> a.each_with_index{ |r, idx| r << 'a' }
=> [["a", "a", "a"], ["a", "a", "a"], ["a", "a", "a"]]
irb(main):004:0> b.each_with_index{ |r, idx| r << 'a' }
=> [["a"], ["a"], ["a"]]
答案 0 :(得分:2)
使用discoveredelements = []
def func():
# a new var is created in the scope of this function
discoveredelements = [1,2,3,4]
func()
print (discoveredelements)
discoveredelements = []
def func():
# declare as global
global discoveredelements
# assign to the global var
discoveredelements = [1,2,3,4]
func()
print (discoveredelements)
方法时:
由于所有Array元素都存储相同的哈希值,因此对其中一个哈希值的更改将影响它们。
如果你想要多个副本,你应该使用每次需要初始化数组元素时使用该块结果的块版本:
.new
请阅读此处的示例 - https://ruby-doc.org/core-2.2.0/Array.html#method-c-new