Ruby 中的私有方法:
如果一个方法在 Ruby 中是私有的,那么它就不能被显式的接收者(对象)调用。它只能被隐式调用。它可以被描述它的类以及这个类的子类隐式调用。
下面的例子将更好地说明它:
1) 具有私有方法 class_name 的 Animal 类
class Animal
def intro_animal
class_name
end
private
def class_name
"I am a #{self.class}"
end
end
在这种情况下:
n = Animal.new
n.intro_animal #=>I am a Animal
n.class_name #=>error: private method `class_name' called
2) Animal 的一个子类,称为 Amphibian:
class Amphibian < Animal
def intro_amphibian
class_name
end
end
在这种情况下:
n= Amphibian.new
n.intro_amphibian #=>I am a Amphibian
n.class_name #=>error: private method `class_name' called
如您所见,私有方法只能被隐式调用。它们不能被显式接收者调用。出于同样的原因,不能在定义类的层次结构之外调用私有方法。
Ruby 中的受保护方法:
如果一个方法在 Ruby 中是受保护的,那么它可以被定义类及其子类隐式调用。此外,它们也可以由显式接收者调用,只要接收者是自己或与自己属于同一类:
1) 具有受保护方法protect_me 的Animal 类
class Animal
def animal_call
protect_me
end
protected
def protect_me
p "protect_me called from #{self.class}"
end
end
在这种情况下:
n= Animal.new
n.animal_call #=> protect_me called from Animal
n.protect_me #=>error: protected method `protect_me' called
2)从动物类继承的哺乳动物类
class Mammal < Animal
def mammal_call
protect_me
end
end
在这种情况下
n= Mammal.new
n.mammal_call #=> protect_me called from Mammal
3)从Animal类继承的两栖类(与哺乳动物类相同)
class Amphibian < Animal
def amphi_call
Mammal.new.protect_me #Receiver same as self
self.protect_me #Receiver is self
end
end
在这种情况下
n= Amphibian.new
n.amphi_call #=> protect_me called from Mammal
#=> protect_me called from Amphibian
4) 一个名为 Tree 的类
class Tree
def tree_call
Mammal.new.protect_me #Receiver is not same as self
end
end
在这种情况下:
n= Tree.new
n.tree_call #=>error: protected method `protect_me' called for #<Mammal:0x13410c0>