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!
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. Returnstrueif the student was enrolled and has now been removed, otherwise returnsfalse. 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, returningtrueif they are andfalseotherwise.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.
We’ll start by defining our EnrollmentSystem class and initializing it with a hash to store enrollments.
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.
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.
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.
We see here that after enrolling Alice in "Math101," the course is listed in @courses_enrollment with Alice as the only student.
