(6 ratings)   
By: math.umd.edu
Now we will learn how to do things with the address book. Especifically, we will learn how to print and how to sort the addressbook.
Added: 23 June 2008    Views: 126  
PathComputers    Programming    Ruby
Keywords: computers   programming   ruby   coder   code   language   print   complex   address   book  
Do you like this tutorial? Now you can support our team to add more :     
 
 
 

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:

Melissa
Joe
Sandy

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

About the Author :
math.umd.edu
Printing the addressbook RUBY
Articles and Tutorials Directory by www.learnfobia.com
 Rate this tutorial : Rate 1Rate 2Rate 3Rate 4Rate 5
  |    Add to Favorites
  |    Send to Friend
  |    Print
Comments