Bhu*_*dha 3 ruby private public
Ruby作为面向对象的语言.这意味着我发送的任何消息,我严格地发送它在类的一些对象/实例上.
例:
class Test
def test1
puts "I am in test1. A public method"
self.test2
end
def test2
puts "I am in test2. A public Method"
end
end
Run Code Online (Sandbox Code Playgroud)
有意义我test2在self对象上调用方法
但我不能这样做
class Test
def test1
puts "I am in test1. A public method"
self.test2 # Don't work
test2 # works. (where is the object that I am calling this method on?)
end
private
def test2
puts "I am in test2. A private Method"
end
end
Run Code Online (Sandbox Code Playgroud)
当test2是public method我可以调用它self(很公平,发送到自我对象的方法).但是,当test2是private method我不能把它的自我.那么我发送方法的对象在哪里?
Tod*_*obs 11
在Ruby中,不能使用显式接收器直接调用私有方法; 自我在这里没有得到任何特殊待遇.根据定义,当你打电话给self.some_method你时,你将self指定为显式接收器,所以Ruby说"不!"
Ruby有方法查找规则.规则可能有更规范的来源(除了转到Ruby源),但是这篇博文在顶部列出了规则:
1) Methods defined in the object’s singleton class (i.e. the object itself)
2) Modules mixed into the singleton class in reverse order of inclusion
3) Methods defined by the object’s class
4) Modules included into the object’s class in reverse order of inclusion
5) Methods defined by the object’s superclass, i.e. inherited methods
Run Code Online (Sandbox Code Playgroud)
换句话说,首先在自己中查找私有方法而不需要(或允许)显式接收器.
我发送方法的对象在哪里
是的self.如果你没有指定接收器,接收器就是self.
privateRuby中的定义是私有方法只能在没有接收器的情况下调用,即使用隐式接收器self.有趣的是,它并没有打扰你的puts方法,这也是一个私有实例方法;-)
注意:此规则有例外.只要接收器是,就可以使用显式接收器调用专用setter self.实际上,必须使用显式接收器调用它们,否则会出现局部变量赋值的模糊性:
foo = :fortytwo # local variable
self.foo = :fortytwo # setter
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1555 次 |
| 最近记录: |