Skip to content

Instantly share code, notes, and snippets.

@leikind
Last active December 14, 2015 12:49
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 leikind/5089212 to your computer and use it in GitHub Desktop.
Save leikind/5089212 to your computer and use it in GitHub Desktop.
# difference between private and protected in Ruby
class Person
def initialize age
@age = age
end
def compare1(another_person)
# this works because #age is protected
self.age <=> another_person.age
end
def compare2(another_person)
# this fails because #age2 is private
self.age2 <=> another_person.age2
end
protected
def age
@age
end
private
def age2
@age
end
end
peter = Person.new(42)
mary = Person.new(30)
puts peter.compare1(mary)
# This throws an exception!!!
puts peter.compare2(mary)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment