Menu
Coddy logo textTech

Top Students

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

Final method, find every student whose average grade is above some threshold.

This is your data pipeline at full strength: iterate, filter on a derived value, return names.

challenge icon

Challenge

Medium

Add a method top_students(threshold) that returns an array of names whose average grade is greater than threshold. Reuse average_grade internally, don't recompute the math. Skip students with no grades (their average is 0 and won't pass any positive threshold).

Names should appear in insertion order; if no one qualifies, return [].

Replace the test block with:

add_student("Alice", 20, ["Math"])
add_student("Bob",   22, ["Biology"])
add_student("Cara",  19, ["Physics"])
add_grade("Alice", 90)
add_grade("Alice", 85)
add_grade("Bob",   70)
add_grade("Cara",  60)
puts top_students(80).inspect
puts top_students(50).inspect
puts top_students(100).inspect

Expected output ends with:

["Alice"]
["Alice", "Bob", "Cara"]
[]

Cheat sheet

Use top_students(threshold) to filter students by average grade, reusing average_grade:

def top_students(threshold)
  $students
    .select { |s| average_grade(s[:name]) > threshold }
    .map    { |s| s[:name] }
end

Students with no grades return 0 from average_grade and are naturally excluded by any positive threshold.

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

def list_by_course(course)
  $student_records.select { |_, info| info[:courses].include?(course) }.keys
end

# TODO: def top_students(threshold), names whose average_grade > threshold

add_student("Alice", 20, ["Math"])
add_student("Bob",   22, ["Biology"])
add_student("Cara",  19, ["Physics"])
add_grade("Alice", 90)
add_grade("Alice", 85)
add_grade("Bob",   70)
add_grade("Cara",  60)
puts top_students(80).inspect
puts top_students(50).inspect
puts top_students(100).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