Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 780
Simplicity Avatar asked Nov 28 '22 18:11

Simplicity


1 Answers

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...
like image 128
Mchl Avatar answered Dec 05 '22 01:12

Mchl