private未阻止对模块(Ruby)中函数的调用
也要阻止第一个调用,但我想知道模块中是否有私有的用例。简单地说,您将模块包含在当前所在的类中。您正在运行当前所处的类中的方法 所以它工作了——就像它应该的那样private未阻止对模块(Ruby)中函数的调用,ruby,private,Ruby,Private,也要阻止第一个调用,但我想知道模块中是否有私有的用例。简单地说,您将模块包含在当前所在的类中。您正在运行当前所处的类中的方法 所以它工作了——就像它应该的那样 private_class_method :secret 开始理解Ruby中私有方法的一个好方法是将其看作只能隐式调用的方法。这意味着不应显式指定接收方法的对象: class CA include Test end CA.new.secret # THIS shouldn't work include Test se
private_class_method :secret
开始理解Ruby中私有方法的一个好方法是将其看作只能隐式调用的方法。这意味着不应显式指定接收方法的对象:
class CA
include Test
end
CA.new.secret # THIS shouldn't work
include Test
secret # THIS should
使用这种简单的方法,您可以(在某种程度上)确保私有方法不会在self
之外的对象上调用。例如:
my_private_method # Implicit call, this is OK.
self.my_private_method # Explicit call, this won't work.
secret #=> "<>"
class MyClass
secret
end #=> "<>"
现在,当您有一个定义私有方法的模块时,您首先需要将其包含在某个地方,以便能够使用该方法。您在示例中所做的是在最顶层包含模块。当您这样做时,Ruby将模块包含在。这意味着您的secret
方法现在是所有Ruby对象的私有方法,并且由于所有Ruby对象都将具有私有secret
方法,您现在可以从程序中的任何位置隐式调用它:
my_private_method # Calling private method on self, this is OK.
other_object.its_private_method # Calling other object's private method, this won't work.
您可以从类中调用类的私有方法,包括由包含的模块添加的私有方法。这就是Ruby中
private
的语义。您永远不能使用显式接收器调用私有方法,即使在包含该方法的类中也是如此。
secret #=> "<>"
class MyClass
secret
end #=> "<>"
module M
private
def my_private_method
"This is private."
end
end
class C
include M
def my_public_method
"<#{my_private_method}>"
end
end
c = C.new
c.my_public_method #=> "<This is private.>"
c.my_private_method #=> This won't work.