Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Build an Address Book in Ruby!
You have completed Build an Address Book in Ruby!
Preview
In this video, we're going to create a class that will store our phone numbers.
Code Samples
Phone Number Class (phone_number.rb):
class PhoneNumber
attr_accessor :kind, :number
def to_s
"#{kind}: #{number}"
end
end
Contact Class
require "./phone_number"
class Contact
attr_writer :first_name, :middle_name, :last_name
attr_reader :phone_numbers
def initialize
@phone_numbers = []
end
def add_phone_number(kind, number)
phone_number = PhoneNumber.new
phone_number.kind = kind
phone_number.number = number
phone_numbers.push(phone_number)
end
def first_name
@first_name
end
def middle_name
@middle_name
end
def last_name
@last_name
end
def first_last
first_name + " " + last_name
end
def last_first
last_first = last_name
last_first += ", "
last_first += first_name
if !@middle_name.nil?
last_first += " "
last_first += middle_name.slice(0, 1)
last_first += "."
end
last_first
end
def full_name
full_name = first_name
if !@middle_name.nil?
full_name += " "
full_name += middle_name
end
full_name += ' '
full_name += last_name
full_name
end
def to_s(format = 'full_name')
case format
when 'full_name'
full_name
when 'last_first'
last_first
when 'first'
first_name
when 'last'
last_name
else
first_last
end
end
def print_phone_numbers
puts "Phone Numbers"
phone_numbers.each { |phone_number| puts phone_number }
end
end
jason = Contact.new
jason.first_name = "Jason"
jason.last_name = "Seifer"
jason.add_phone_number("Home", "123-456-7890")
jason.add_phone_number("Work", "456-789-0123")
puts jason.to_s('full_name')
jason.print_phone_numbers
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
but wouldn't we also want to
enter a contact's phone number?
0:00
Yes we would.
0:04
So what we're going to do is create
a class to store phone numbers.
0:05
So hit File > New.
0:10
And we'll call this class phone_number.
0:12
And we create a phone_number.rb.
0:16
Now we can create our PhoneNumber class.
0:19
And this is gonna be
a really simple class.
0:23
We're not really gonna be working with
phone numbers too much by themselves.
0:27
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up