Applying Data Filtering and Aggregation in a User Management System

Introduction

Welcome to today’s lesson on applying data filtering and aggregation in a real-world scenario through a user management system. We’ll start by building a foundational structure that can handle basic user operations, then gradually expand it by introducing more advanced functionalities to allow filtering and aggregating user data.

Starter Task Methods

In our starter task, we’ll implement a class to manage basic operations on a collection of user data, specifically handling the addition of new users, retrieving user profiles, and updating existing user profiles. Here are the methods we’ll begin with:

  • add_user(user_id, age, country, subscribed) — Adds a new user with specified attributes. Returns true if the user is added successfully; returns false if a user with the same user_id already exists.
  • get_user(user_id) — Retrieves the user’s profile as a hash if the user exists; returns nil if the user does not exist.
  • update_user(user_id, age = nil, country = nil, subscribed = nil) — Updates the user’s profile with provided parameters. Returns true if the user exists and was updated, and false otherwise.

Implementing Basic User Management

Let’s begin by creating a UserManager class that manages user data within a hash structure, @users, where each key is a user_id and each value is a hash representing the user’s profile.

class UserManager
  def initialize
    @users = {}
  end
end

The initialize method sets up an empty hash, @users, which will store all user profiles.

Adding and Retrieving Users

The add_user and get_user methods handle adding new users and retrieving existing user profiles.

def add_user(user_id, age, country, subscribed)
  return false if @users.key?(user_id)

  @users[user_id] = { age: age, country: country, subscribed: subscribed }
  true
end

def get_user(user_id)
  @users[user_id]
end

In add_user, we check if a user with the specified user_id already exists. If not, we create a new entry in @users with the user’s details and return true. If the user already exists, it returns false. The get_user method retrieves a user’s profile from @users, returning the profile if found or nil if the user does not exist.

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