Simplicity
Simplicity

Reputation: 48916

Ruby - Protected method

I have the following Ruby program:

class Access

def retrieve_public
puts "This is me when public..."
end

private
def retrieve_private
puts "This is me when privtae..."
end

protected
def retrieve_protected
puts "This is me when protected..."
end

end


access = Access.new
access.retrieve_protected

When I run it, I get the following:

accessor.rb:23: protected method `retrieve_protected' called for #<Access:0x3925
758> (NoMethodError)

Why is that?

Thanks.

Upvotes: 4

Views: 7881

Answers (3)

Steve007
Steve007

Reputation: 251

The protected access control in Ruby can be confusing at first. The problem is that you'll often read protected methods in Ruby can only be called by an explicit receiver of "self" or an sub-instance of the "self" Class whatever that class maybe. And that is not exactly true.

The real deal with Ruby protected methods is that you may only call a protected methods with an explicit receiver in the "context" an instances of the class or sub-classes that you've defined those methods in. If you try to call a protected method with an explicit receiver with in context that is not the class or sub-classes where you defined the methods you'll get an error.

Upvotes: 0

Mchl
Mchl

Reputation: 62377

Because you can call protected methods directly only from within instance method of this object, or or another object of this class (or subclass)

class Access

  def retrieve_public
    puts "This is me when public..."
    retrieve_protected

    anotherAccess = Access.new
    anotherAccess.retrieve_protected 
  end

end

#testing it

a = Access.new

a.retrieve_public

# Output:
#
# This is me when public...
# This is me when protected...
# This is me when protected...

Upvotes: 14

numbers1311407
numbers1311407

Reputation: 34072

This is what protected methods are all about in Ruby. They can only be called if the receiver is self or of the same class hierarchy as self. Protected methods are typically used internally in instance methods.

See http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Protected

You can always circumvent this behavior by sending the method, e.g.

access.send(:retrieve_protected)

Although this could be considered bad practice as it's deliberately circumventing the access restrictions imposed by the programmer.

Upvotes: 13

Related Questions