小编Gna*_*wme的帖子

为什么Ruby类允许通过方法返回来访问实例变量?

我有一个同事的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实例变量的引用 …

ruby encapsulation reference instance-variables

0
推荐指数
1
解决办法
112
查看次数