Created
August 6, 2020 15:15
-
-
Save jadon1979/27273c0cdf044bf71ad47855c80fafcc to your computer and use it in GitHub Desktop.
public, private, protected
This file contains hidden or 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
| bob = Person.new('Bob', 'Smith', 'bob@example.com', '444-333-4444') | |
| john = Person.new('John', 'Smith', 'john@example.com', '555-444-3333') | |
| # full_nane is a public method | |
| bob.full_name | |
| # => "Smith, Bob" | |
| john.full_name | |
| # => "Smith, John" | |
| # email is a protected method. | |
| bob.email | |
| # => protected method `email' called for #<Person:0x0000559fb5b50e00> | |
| # ssn is a private method. | |
| bob.ssn | |
| # => private method `ssn' called for #<Person:0x000055a1f6f21550> | |
| bob.talk_to(john, 'Hey friend') | |
| # => mailto:john@example.com | |
| # Hey friend | |
| # in the #talk_to method we have access to friend.email because email is a protected method and we are calling it | |
| # from within the class it was created. We would also have access to this from any class that subclasses the | |
| # Person class. Since both Bob and John are of the same class then they can share email with eachother. | |
| # We would not have access to #ssn though. #ssn is private. John and Bob may be of the same class, but they | |
| # cannot share their ssn with eachother. Each of their #ssn methods are only accessible to their own instances. |
This file contains hidden or 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 DummyEmail | |
| def self.send_mail(email, message) | |
| puts "mailto:#{email}\n#{message}" | |
| end | |
| end | |
| class Person | |
| def initialize(first_name, last_name, email, ssn, mailer = DummyEmail) | |
| @first_name = first_name | |
| @last_name = last_name | |
| @email = email | |
| @ssn = ssn | |
| @mailer = mailer | |
| end | |
| def full_name | |
| "#{@last_name}, #{@first_name}" | |
| end | |
| def talk_to(friend, message) | |
| @mailer.send_mail(friend.email, message) | |
| end | |
| protected | |
| attr_reader :email | |
| private | |
| attr_reader :ssn | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment