我有一个同事的Ruby代码:
class Leaky
def initialize
@internalOnly = [[1, 2, 3], [3, 4, 5]]
end
def foo
if 5 > 4
temp = @internalOnly
end
end
def printInternal
puts " here is my @internalOnly: #{@internalOnly}"
end
end
a = Leaky.new
a.printInternal
b = a.foo # 1) Gets Leaky:@internal!
b[1] = 666 # 2) Modifies it!
a.printInternal
Run Code Online (Sandbox Code Playgroud)
它产生这个输出:
here is my @internalOnly: [[1, 2, 3], [3, 4, 5]]
here is my @internalOnly: [[1, 2, 3], 666]
Run Code Online (Sandbox Code Playgroud)
在语句中# 1),Ruby显然返回了对Leaky实例变量的引用 …