【发布时间】:2013-11-15 10:54:42
【问题描述】:
我认为在调用私有方法时放置显式接收器是不可接受的。好吧,我在 Ruby 2.0 中做了这个,我可以得到结果:
class Test
def public_method
self.set_size=10
end
def return_size
@size
end
private
def set_size=(size)
@size = size
end
end
test = Test.new
test.public_method
p test.return_size
这是为什么?
【问题讨论】:
-
您为什么认为这是不可接受的?我看起来可以接受。
-
不是我想的,它在文档中:
Private methods cannot be called with an explicit receiver - the receiver is always self. This means that private methods can be called only in the context of the current object; you cannot invoke another object's private methods. -
@HommerSmith:你在 self 上调用方法......这没有什么问题。
-
访问限制。不是语法限制。我会将其解释为“......不能用显式接收器调用 self 以外的,因为接收器始终是 self”
-
@Linuxios 即使
self不是setter 方法也会挂起。如果我们发送的方法是 setter,那么显式接收器(self 或其他)是正确的。
标签: ruby