Skip to content

Instantly share code, notes, and snippets.

@leoallen85
Created February 28, 2013 16:47
Show Gist options
  • Save leoallen85/5058108 to your computer and use it in GitHub Desktop.
Save leoallen85/5058108 to your computer and use it in GitHub Desktop.
This shows public, private, and protected methods in Ruby. This is a way of controlling which methods can be accessed from outside the object
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