Skip to content

Instantly share code, notes, and snippets.

@makersacademy
Forked from leoallen85/public_and_protected.rb
Created February 28, 2013 17:29
Show Gist options
  • Save makersacademy/5058483 to your computer and use it in GitHub Desktop.
Save makersacademy/5058483 to your computer and use it in GitHub Desktop.
class Base
def public_method
puts 'public method called'
end
# This works as we are calling the private method
# from within the object
def call_private_method
private_method
end
private
def private_method
puts 'private method called'
end
protected
def protected_method
puts 'protected method called'
end
end
class Child < Base
# This will fail as we cannot call a private
# method in a child class
def call_private_method
private_method
end
# This will work however as a protected method
# we can call in the child class
def call_protected_method
protected_method
end
end
base, child = Base.new, Child.new
# These will succeed
base.public_method
child.public_method
base.call_private_method
# This will fail as we are calling it from
# outside the class
base.private_method
# This will fail as we are calling it from
# outside the class
base.protected_method
# Will fail, see notes in class method
child.call_private_method
# Will succeed
child.call_protected_method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment