class Example
private
def example_test
puts 'Hello'
end
end
e = Example.new
e.example_test
这当然行不通,因为我们指定了示例(e
)的显式接收方实例,这违反了"私有规则".
但我不明白,为什么一个人不能在Ruby中这样做:
class Foo
def public_m
self.private_m # <=
end
private
def private_m
puts 'Hello'
end
end
Foo.new.public_m
public_m
方法定义(即self
)中的当前对象是Foo的实例.那为什么不允许呢?为了解决这个问题,我必须将self.private_m
改为private_m
.但是为什么这不同呢,self
不是Foo在public_m
中的一个例子吗?谁是裸字private_m
呼叫的接受者?这不是self
吗?实际上你忽略了什么,因为Ruby会为你做这件事(会自己打电话给private_m)?
我希望我没有把它搞糊涂,我对Ruby还很 fresh .
编辑:
class Example
# self as an explicit receiver (will throw an error)
def explicit
self.some_private_method
end
# self as an implicit receiver (will be ok)
def implicit
some_private_method
end
private
def some_private_method; end
end
Example.new.implicit
给在谷歌追踪中发现这个问题的人的信息:这可能会有帮助-http://weblog.jamisbuck.org/2007/2/23/method-visibility-in-ruby