Building an Address Book Application with Hashes
Introduction
Welcome! In this lesson, we’ll explore creating a simple address book application using Ruby hashes. This exercise will strengthen your understanding of hashes in Ruby, specifically in adding, retrieving, and deleting entries.
By the end of this lesson, you’ll have a solid grasp of these fundamental operations and how they’re applied in practical programming tasks.
Introducing Methods to Implement
In this task, we’ll build three core methods to manage our address book:
add_contact(name, phone_number): Adds a new contact. If the contact already exists, it returnsfalseand does not overwrite the number; otherwise, it adds the contact and returnstrue.get_contact(name): Retrieves the phone number for a givenname. If the contact does not exist, it returnsnil.delete_contact(name): Deletes a contact with the specifiedname. Returnstrueif the contact was successfully deleted andfalseif the contact does not exist.
Let’s walk through each method in detail.
Step 1: Implementing add_contact
This method will add a new contact with the given name and phone_number. If the contact already exists, it returns false; otherwise, it adds the contact and returns true.
Question: Why is it important to check if a contact already exists before adding?
Answer: To avoid duplicating contacts and prevent overwriting existing information, which can lead to data inconsistency.
Here’s how we implement this method:
In this method:
- We check if the contact already exists with
if @contacts.key?(name). - If it exists, we return
false. - If it doesn’t exist, we add it to the hash and return
true.
Step 2: Implementing get_contact
