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:

  1. add_contact(name, phone_number): Adds a new contact. If the contact already exists, it returns false and does not overwrite the number; otherwise, it adds the contact and returns true.
  2. get_contact(name): Retrieves the phone number for a given name. If the contact does not exist, it returns nil.
  3. delete_contact(name): Deletes a contact with the specified name. Returns true if the contact was successfully deleted and false if 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:

class AddressBook
  def initialize
    @contacts = {}  # Initialize an empty hash to store contacts
  end
  
  def add_contact(name, phone_number)
    if @contacts.key?(name)  # Check if contact already exists
      return false
    end
    @contacts[name] = phone_number  # Add new contact
    true
  end
end

# Example usage:
address_book = AddressBook.new
puts address_book.add_contact("Alice", "123-456-7890")  # true
puts address_book.add_contact("Alice", "098-765-4321")  # false
puts address_book.inspect  # {"Alice"=>"123-456-7890"}

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
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal