Skip to content

Instantly share code, notes, and snippets.

@jadon1979
Created August 6, 2020 15:15
Show Gist options
  • Select an option

  • Save jadon1979/27273c0cdf044bf71ad47855c80fafcc to your computer and use it in GitHub Desktop.

Select an option

Save jadon1979/27273c0cdf044bf71ad47855c80fafcc to your computer and use it in GitHub Desktop.
public, private, protected
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.
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