Menu
Coddy logo textTech

List By Course

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 52 of 56.

Add a method that finds every student enrolled in a given course and returns their names as an array. This is the kind of select/map chain you've already practiced.

challenge icon

Challenge

Easy

Add a method list_by_course(course) that returns an array of names of students whose :courses array includes course. Names should appear in insertion order; if no one is enrolled, return [].

Replace the test block with:

add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob",   22, ["Biology", "Math"])
add_student("Cara",  19, ["Physics"])
puts list_by_course("Math").inspect
puts list_by_course("Physics").inspect
puts list_by_course("Art").inspect

Expected output:

Student 'Alice' added.
Student 'Bob' added.
Student 'Cara' added.
["Alice", "Bob"]
["Alice", "Cara"]
[]

Cheat sheet

Use select + map to filter students by a field and return names:

def list_by_course(course)
  @students.select { |s| s[:courses].include?(course) }
           .map    { |s| s[:name] }
end

Try it yourself

$student_records = {}

def add_student(name, age, courses)
  if $student_records.key?(name)
    puts "Student '#{name}' already exists."
    return
  end
  $student_records[name] = { age: age, grades: [], courses: courses }
  puts "Student '#{name}' added."
end

def add_grade(name, grade)
  unless $student_records.key?(name)
    puts "Student '#{name}' not found."
    return
  end
  $student_records[name][:grades] << grade
  puts "Grade #{grade} added for '#{name}'."
end

def average_grade(name)
  unless $student_records.key?(name)
    puts "Student '#{name}' not found."
    return nil
  end
  grades = $student_records[name][:grades]
  return 0 if grades.empty?
  grades.sum.to_f / grades.length
end

# TODO: def list_by_course(course), return array of names enrolled in `course`

add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob",   22, ["Biology", "Math"])
add_student("Cara",  19, ["Physics"])
puts list_by_course("Math").inspect
puts list_by_course("Physics").inspect
puts list_by_course("Art").inspect
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow