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
Contacts are going to have both phone numbers and addresses. In this video, we're going to define the `to_s` method on the address class and have it be able to take a formatting argument.
Code Samples
Address.rb:
class Address
attr_accessor :kind, :street_1, :street_2, :city, :state, :postal_code
def to_s(format = 'short')
address = ''
case format
when 'long'
address += street_1 + "\n"
address += street_2 + "\n" if !street_2.nil?
address += "#{city}, #{state} #{postal_code}"
when 'short'
address += "#{kind}: "
address += street_1
if street_2
address += " " + street_2
end
address += ", #{city}, #{state}, #{postal_code}"
end
address
end
end
home = Address.new
home.kind = "Home"
home.street_1 = "123 Main St."
home.city = "Portland"
home.state = "OR"
home.postal_code = "12345"
puts home.to_s('short')
puts "\n"
puts home.to_s('long')
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
we're going to have to write our own.
0:00
Get it?
0:00
Addressed?
0:01
It's a bad pun about addresses.
0:02
Anyway, we'll be writing
our own address class now
0:04
in addition to another supporting
class for our program.
0:07
Let's get to it using workspaces.
0:10
So our contacts have phone numbers.
0:13
Now let's go ahead and
have addresses for our contacts as well.
0:15
Now we can do that by creating
another class for an address.
0:20
So we'll go ahead and create a new file,
you can do that by right clicking and
0:26
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