Created
August 1, 2014 17:27
-
-
Save rupurt/21ac1d15dc4a0925955f to your computer and use it in GitHub Desktop.
Ruby public/private/protected
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
class PublicPerson | |
def initialize(name) | |
@name = name | |
end | |
def say_name | |
puts @name | |
end | |
def say_other_name(person) | |
person.say_name | |
end | |
end | |
class PrivatePerson | |
def initialize(name) | |
@name = name | |
end | |
def say_other_name(person) | |
person.say_name | |
end | |
private | |
def say_name | |
puts @name | |
end | |
end | |
class ProtectedPerson | |
def initialize(name) | |
@name = name | |
end | |
def say_other_name(person) | |
person.say_name | |
end | |
protected | |
def say_name | |
puts @name | |
end | |
end | |
public_person1 = PublicPerson.new("Alex") | |
public_person2 = PublicPerson.new("Kate") | |
public_person1.say_other_name(public_person2) # => "Kate" | |
private_person1 = PrivatePerson.new("Alex") | |
private_person2 = PrivatePerson.new("Kate") | |
private_person1.say_other_name(private_person2) # => NoMethodError: private method `say_name' called for #<PrivatePerson:0x007f908e2631f0 @name="Kate"> | |
protected_person1 = ProtectedPerson.new("Alex") | |
protected_person2 = ProtectedPerson.new("Kate") | |
protected_person1.say_other_name(protected_person2) # => "Kate" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment