Introduction

Welcome to today’s lesson! We’ll explore how to use Ruby’s Set class in a practical context by creating a student enrollment system for courses. Imagine you’re managing enrollments for an online course platform, where students enroll in courses, check their enrollments, or get a list of classmates. Using Set is ideal here since it automatically prevents duplicates, ensuring each student can only enroll in a course once.

By the end of this lesson, you’ll have a solid understanding of how to use sets and hashes for handling unique collections. Let’s get started!

Introducing Methods to Implement

In this system, we’ll build four methods for managing student enrollments:

  • enroll(student, course): Adds a student to a course. If the student is already enrolled, it does nothing.
  • unenroll(student, course): Removes a student from a course. Returns true if the student was enrolled and has now been removed, otherwise returns false. If the course becomes empty after unenrolling the student, it should also be removed from the system.
  • is_enrolled(student, course): Checks if a student is enrolled in a course, returning true if they are and false otherwise.
  • list_students(course): Returns an array of all students enrolled in a given course. If no students are enrolled, it returns an empty array.

Let’s implement each method one step at a time.

Step 1: Define the Class

We’ll start by defining our EnrollmentSystem class and initializing it with a hash to store enrollments.

require 'set'

class EnrollmentSystem
  def initialize
    @courses_enrollment = {}  # Hash to store each course with its enrolled students
  end
end

This code sets up an empty courses_enrollment hash, where each course will map to a set of students. Now that we have our class structure, let’s move to the methods.

Step 2: Implement enroll Method

The enroll method adds a student to a course. If the course doesn’t exist yet in @courses_enrollment, we’ll create a new set for it.

def enroll(student, course)
  @courses_enrollment[course] ||= Set.new  # Initialize set if course doesn't exist
  @courses_enrollment[course].add(student) # Add student to the course's set
end

This method first checks if the course exists in @courses_enrollment. If it doesn’t, @courses_enrollment[course] ||= Set.new creates a new set for that course. Then, the student is added to the course’s set, ensuring the student is only enrolled once.

# Example usage
es = EnrollmentSystem.new
es.enroll("Alice", "Math101")
puts es.inspect  # Output: {"Math101"=>#<Set: {"Alice"}>}

We see here that after enrolling Alice in "Math101," the course is listed in @courses_enrollment with Alice as the only student.

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