Introduction

Welcome! Today, we’re diving into an exciting project that involves managing employee records within a company. Specifically, we’ll use nested hashes and arrays in Ruby to add projects and tasks for employees and retrieve those tasks as needed. This exercise will help you understand how to manipulate nested data structures effectively in Ruby.

Introducing Methods to Implement

We'll implement three methods in our EmployeeRecords class:

  • add_project(employee_id, project_name) - Adds a new project to an employee's list of projects. If the project already exists for that employee, the method returns false. Otherwise, it adds the project and returns true.
  • add_task(employee_id, project_name, task) - Adds a new task to a specified project for an employee. If the project does not exist for that employee, the method returns false. If the task is added successfully, it returns true.
  • get_tasks(employee_id, project_name) - Retrieves all tasks for a specified project of an employee. If the project does not exist for that employee, the method returns nil. Otherwise, it returns the list of tasks.
Step 1: Basic Class Structure

Let’s start by building the basic structure of our EmployeeRecords class and initializing our data storage.

class EmployeeRecords
  def initialize
    @records = {}  # Stores employee data as a hash
  end
end

# Instantiate the class to ensure it initializes correctly
records = EmployeeRecords.new

In this initial setup, we define the EmployeeRecords class and create an instance variable @records, which is an empty hash. This hash will store employee records, with each key being an employee ID and each value being another hash that holds the employee's projects.

Step 2: Implementing `add_project` Method

Next, let’s implement the add_project method to add projects to an employee's record.

class EmployeeRecords
  def initialize
    @records = {}
  end

  def add_project(employee_id, project_name)
    @records[employee_id] ||= {}  # Initialize employee record if it doesn't exist
    if @records[employee_id].key?(project_name)
      false  # Return false if project already exists
    else
      @records[employee_id][project_name] = []  # Initialize an empty task list
      true  # Return true to confirm project was added
    end
  end
end

# Example usage and testing
records = EmployeeRecords.new
puts records.add_project("E123", "ProjectA")  # Output: true
puts records.add_project("E123", "ProjectA")  # Output: false

The add_project method checks if employee_id exists in the @records hash. If not, it initializes a new hash for that employee. It then checks if the project_name already exists for that employee. If it does, the method returns false. Otherwise, it initializes an empty array for the project (to hold tasks) and returns true.

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