webren
webren

Reputation: 620

Ruby Protected Methods Issue

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 protected 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!

Upvotes: 0

Views: 570

Answers (1)

Stefaan Colman
Stefaan Colman

Reputation: 3705

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

Upvotes: 3

Related Questions