Created
November 9, 2018 07:52
-
-
Save ndbroadbent/4dd58d2abfaf5918c520e40f81deed5e to your computer and use it in GitHub Desktop.
Private vs protected in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class A | |
protected | |
def a_protected | |
'can call protected' | |
end | |
private | |
def a_private | |
'can call private' | |
end | |
end | |
class B < A | |
def call_a_protected_with_explicit_self | |
self.a_protected | |
end | |
def call_a_protected_with_implicit_self | |
a_protected | |
end | |
def call_a_private_with_explicit_self | |
self.a_private | |
end | |
def call_a_private_with_implicit_self | |
a_private | |
end | |
def call_a_protected_on_a_instance(a) | |
a.a_protected | |
end | |
end | |
b = B.new | |
b.call_a_protected_with_explicit_self | |
# => "can call protected" | |
b.call_a_protected_with_implicit_self | |
# => "can call protected" | |
b.call_a_private_with_explicit_self | |
# NoMethodError: private method `a_private' called for #<B:0x007fb1ed9cc240> | |
b.call_a_private_with_implicit_self | |
# => "can call private" | |
A.new.a_protected | |
# NoMethodError: protected method `a_protected' called for #<A:0x007fae9881df00> | |
b.call_a_protected_on_a_instance(A.new) | |
# => "can call protected" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment