Introduction

Hello, Space Explorer! Today, we're delving into an essential topic in Ruby: managing data using arrays.

We’ll practice this by building a simple Student Management System that tracks students and their grades. Using arrays in Ruby, we’ll see how to efficiently organize and access data, just as we might in real-world applications. Ready to dive in? Let’s get started!

Introducing Methods to Implement

To achieve our goal, we’ll need three key methods within our class:

  1. add_student(name, grade): Adds a new student and their grade to the list. If the student already exists, their grade will be updated.
  2. get_grade(name): Retrieves the grade for a student by their name. If the student isn’t found, it returns nil.
  3. remove_student(name): Removes a student from the list by their name. It returns true if the student was successfully removed and false if the student doesn’t exist.

Sound straightforward? Fantastic! Let’s walk through each method step-by-step.

Implementing the Solution Step-by-Step

First, we’ll define our StudentManager class, which will use an array to manage students and their grades.

class StudentManager
  def initialize
    @students = []  # Initializes an empty array to store student data
  end
end
Step 1: Implementing add_student

The add_student method adds a new student or updates an existing student’s grade.

def add_student(name, grade)
  @students.each_with_index do |student, i|
    if student[0] == name  # Checks if the student's name matches the provided name
      @students[i] = [name, grade]  # Updates the grade if the student exists
      return
    end
  end
  @students.push([name, grade])  # Adds a new student if no match was found
end
  • We use each_with_index to loop through @students.
  • If we find a student with the same name, we update their grade.
  • If not, we add a new array [name, grade] to the list.

Why check if the student already exists? Correct, to prevent duplicate entries and ensure data consistency!

Step 2: Implementing get_grade

The get_grade method finds and returns the grade for a student by their name.

def get_grade(name)
  @students.each do |student|
    return student[1] if student[0] == name  # Returns the grade if name matches
  end
  nil  # Returns nil if no matching student is found
end

This method works by:

  • Looping through @students.
  • Returning the grade if a matching name is found.
  • Returning nil if the student is not found.

Can you think of situations where a student might not be found? Right — they might be new students, or there could be a typo in their name.

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