<- Sorting the addressbook
About this chapter ->

Good programming techniques

Array or hash?

When should I use an array? When should I use a hash?

The addressbook structure is a good example of when you should use each.

In the addressbook example, the address and person structures contained disparate data. So we represented them as hashes.

The addressbook itself contained data in the same category (persons) and we also wanted to be able to sort it. So an array was the best choice.

Variable names

As you write more complex data structures, it becomes more important that you pick good variable names.

Arrays

An array should represent a collection of "equal" things. Like a group of cars, a group of names, etc. You can reflect this by using a plural for your array name. For example:

  • If each array element is a car, the array should be called cars.

  • If each array element is a name, the array should be called names.

This way, the variable name reminds you that that this is an array, and at the same time it reads like English.

Hashes

When dealing with hashes, it is important that you pick good names for the hash keys. A good name is one that is clear, descriptive and easy to remember:

Good key name: "first name"
Bad key name: "1stname"

Since keys are allowed to have spaces, there is no excuse for having "1stname" for a key.

Comments

As you write more complex programs, it becomes more important that you include clear comments that explain what you are trying to do.

Nesting structures

In general, it is best to not nest structures too deeply. If you use proper indentation and good names, it might be alright.

Take a look at these examples:

Good:


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

# Joe
joe = {
    "first name" => "Joe",
    "last name"  => "Smith",
    "address"    => joe_addr
}
                       

Not as good:


# Joe
joe = {
    "first name" => "Joe",
    "last name"  => "Smith",
    "address"    => {
        "street" => "43 Main St. W",  
        "city"   => "Washington",
        "state"  => "DC",
        "zip"    => "29847"
         }
}
                       

Bad:


joe = {
"first name" => "Joe",
"last name" => "Smith",
"address" => {
"street" => "43 Main St. W",  
"city" => "Washington",
"state" => "DC", "zip" => "29847"  
}}
                       
<- Sorting the addressbook
About this chapter ->