Last active
December 14, 2015 12:49
-
-
Save leikind/5089212 to your computer and use it in GitHub Desktop.
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
# 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