Printing the addressbook
Now we will learn how to do things with the address book.
Specifically, we will learn how to print and how to sort the
addressbook.
Printing complex structures
You can still type "puts addressbook", but the
output is ugly and not very useful (try it and see for yourself).
We would rather define our own way of printing its contents.
The addressbook is an array, so we have the Array#each
method. Let's start by just printing the first names of the
contacts:
addressbook.each do |person|
puts person["first name"]
end
|
This will print:
Full names
The next step is to print full names:
addressbook.each do |person|
first = person["first name"]
last = person["last name"]
puts first + " " + last
end
|
Which prints:
Melissa Adams
Joe Smith
Sandy Koh
|
Phone number:
addressbook.each do |person|
first = person["first name"]
last = person["last name"]
phone = person["phone"]
puts first + " " + last + ":"
puts " " + phone
end
|
Output:
Melissa Adams:
(301) 364-8924
Joe Smith:
(301) 345-9837
Sandy Koh:
(301) 354-2975
|
Address
Finally add the address and a sepparation between the entries.
addressbook.each do |person|
# Name and phone.
first = person["first name"]
last = person["last name"]
phone = person["phone"]
puts first + " " + last + ":"
puts " " + phone
# Address
street = person["address"]["street"]
city = person["address"]["city"]
state = person["address"]["state"]
zip = person["address"]["zip"]
puts " " + street
puts " " + city
puts " " + state + ", " + zip
# A blank line to sepparate entries.
puts ""
end
|
Which produces:
Melissa Adams:
(301) 364-8924
23 St George St.
Silver Spring
MD, 20465
Joe Smith:
(301) 345-9837
43 Main St. W
Washington
DC, 29847
Sandy Koh:
(301) 354-2975
324 Campus Dr.
College Park
MD, 23659
|