Rod*_*igo 12 ruby protected nomethoderror
我有这个小代码似乎在某种程度上与Ruby的文档相矛盾:
第二个可见性是
protected.当调用受保护的方法时,发送方必须是接收方的子类,或者接收方必须是发送方的子类.否则NoMethodError将提出一个.
class Test
def publico(otro)
otro.prot
end
end
class Hija < Test
protected def prot; end
end
Test.new.publico(Hija.new)
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
NoMethodError:为#publico调用的受保护方法`prot'
我错过了什么?显然,选项"接收者必须是发送者的子类"是不可用的.
虽然它不适用于不知道受保护方法的父类,但它适用于定义受保护方法的子类的子类。例如。
class A
def n(other)
other.m
end
end
class B < A
def m
1
end
protected :m
end
class C < B
end
class D < C
end
a = A.new
b = B.new
c = C.new
d = C.new
c.n b #=> 1 -- sender C is a subclass of B
b.n b #=> 1 -- m called on defining class
a.n b # raises NoMethodError although reciever B is a subclass of sender A
b.n c #=> 1 -- reciever C is subclass of sender B
c.n d #=> 1 -- reciever D is sublcass of sender C
Run Code Online (Sandbox Code Playgroud)
我们大概可以得出这样的结论:该行为类似于“发送者或接收者必须继承该方法”。通过这种行为,我们可以解释,由于 A(不知道 m 的存在)和 B(知道 m 的存在但没有继承它)都没有继承该方法,因此会引发错误。
尽管这也有可能是一个错误。
| 归档时间: |
|
| 查看次数: |
174 次 |
| 最近记录: |