<- Hashes
Printing the addressbook ->

Example: Addressbook

In this section we will construct an small addressbook containing contact information for three friends: Joseph, Melissa and Sandy.

An addressbook is a fairly complex structure. It contains several contacts, and each one has an associated name, address and so on.

Our strategy will be to split the problem into simpler ones.

First step: requirements

First, we should figure out what kind of information our address book should have:

  1. The address book contains a group of contacts . We should be able to sort these contacts alphabetically.

  2. Each contact has a first name, last name, phone number and an address.

  3. Each address contains a street, city, state and zip code.

We are going to tackle these starting and the address structure and finishing the the addressbook.

Second step: address

We have a couple of choices for the address structure:

  1. Array: It is customary that the street goes first, then city, then state and last the zip code. So an array might work.

  2. Hash: It is easier to remember something like address["zip"] than address[2]. So, a hash might be easier to use.

In this case, I will pick a hash. So, the three addresses would be:

# Melissa's address
melissa_addr = {
	"street" => "23 St George St.",  
	"city"   => "Silver Spring",
	"state"  => "MD",
	"zip"    => "20465"

# Sandy's address
sandy_addr = {
	"street" => "324 Campus Dr.",
	"city"   => "College Park",
	"state"  => "MD",
	"zip" 	 => "23659"

# Joe's address
joe_addr = {
	"street" => "43 Main St. W",
	"city"   => "Washington",
	"state"  => "DC",
	"zip"    => "29847"

Third step: Persons

Each person has a first name, last name, a phone number and an address. There is no obvious order for these items, so we definitelly need a hash.

# Joe
joe = {
	"first name" => "Joe",
	"last name"  => "Smith",
	"phone"	     => "(301) 345-9837",
	"address"    => joe_addr

# Melissa
melissa = {
	"first name" => "Melissa",
	"last name"  => "Adams",
	"phone"      => "(301) 364-8924",  
	"address"    => melissa_addr

# Sandy
sandy = {
	"first name" => "Sandy",
	"last name"  => "Koh",
	"phone"      => "(301) 354-2975",
	"address"    => sandy_addr

Fourth step: Addressbook

Now that we have all the other structures defined, it is time to create the addressbook. We want the addressbook to retain a particular order. Thus, we must use an array:

addressbook = [ melissa, joe, sandy ]  

And there we are. A complete addressbook structure. In the next section we will learn how to sort this addressbook and do some other nifty things with it.

Note: Make sure that you save all of this in a file. We are going to keep using it in the next few sections.


  1. Add one of your own friends to this addressbook.

  2. Change the addressbook so that it also contains an email address.

<- Hashes
Printing the addressbook ->