Skip to content

Instantly share code, notes, and snippets.

@ndbroadbent
Created November 9, 2018 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ndbroadbent/4dd58d2abfaf5918c520e40f81deed5e to your computer and use it in GitHub Desktop.
Save ndbroadbent/4dd58d2abfaf5918c520e40f81deed5e to your computer and use it in GitHub Desktop.
Private vs protected in Ruby
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