Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
- Contact Class: Part 1 6:05
- Create a Contact Class 1 objective
- Contact Class: Part 2 4:04
- Write a Method 1 objective
- Phone Number Class 6:15
- Write a to_s Method 1 objective
- Address Class: Part 1 5:00
- Address Class: Part 2 3:44
- Initializing and Calling Methods 2 objectives
- Address Book Class 4:25
- Instance variable instantiation 2 objectives

- 2x 2x
- 1.75x 1.75x
- 1.5x 1.5x
- 1.25x 1.25x
- 1.1x 1.1x
- 1x 1x
- 0.75x 0.75x
- 0.5x 0.5x
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 up-
Alphonse Cuccurullo
2,513 Points1 Answer
-
Andrew Walters
8,876 Points2 Answers
-
Adiv Abramson
6,919 Points1 Answer
-
Nicolas Filzi
18,021 Points1 Answer
-
Sarah A. Morrigan
14,329 Points2 Answers
View all discussions for this video
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
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