-1
class User    
  def say_secret_with_self
    self.secret
  end

  protected

  def secret
    "secret"
  end
end

u = User.new
p u.say_secret_with_self   # => "secret"

I have heard that protected methods can be accessed only by inherited members. But the above is possible in ruby. Is it correct code?

Jagdeep Singh
  • 4,750
  • 2
  • 13
  • 22
Sam
  • 4,692
  • 11
  • 38
  • 86
  • `self.secret` can be simplified to `secret` as `self` is the implicit receiver. If, however `secret` were `private` one cannot use an explicit receiver, even `self`; you must write just `secret`. – Cary Swoveland Jul 02 '18 at 06:58
  • What is “inherited members” supposed to mean? Also, if it is possible, it’s a correct code. – Aleksei Matiushkin Jul 02 '18 at 07:05
  • _"Is it possible to access the protected methods outside the class"_ – you don't access the _protected_ method `secret` from outside the class. You access the _public_ method `say_secret_with_self`. The protected method is called from _within_ the class. – Stefan Jul 02 '18 at 08:19

2 Answers2

4

Yes it is correct code. An instance of the class is able to call self methods even if they are protected. protected/private methods are hidden from the outside but not from inside.

Philidor
  • 40,933
  • 9
  • 84
  • 94
2

the method secret is still protected. you cant call it from outside of your class (or inherited class). but you can call it from say_secret_with_self because it is still in the same class with secret

Rafid
  • 551
  • 1
  • 6
  • 18