I have a simple Ruby base class where all the methods need to have protected visibility. The problem arises when another class inherits the base class and calls its methods. The Ruby interpreter stops and tells me the first method it interprets is a protec开发者_Python百科ted method, and tells me the class can't call it. Here is my code:
class Base
protected
def methodOne
# method code
end
def methodTwo
# method code
end
end
The error occurs when the subclass calls a method from the base.
Subclass.new.methodOne
I'm obviously missing something crucial with Ruby's visibility/inheritance model. Any help is appreciated!
You can only call your own and inherited protected methods.
What you are doing is creating an other new object (with Base.new
) and call methodOne
on it. You need to do self.methodOne
Example:
class Extended < Base
def new_method
self.methodOne # calling method one defined in Base
end
end
精彩评论