Menu
Coddy logo textTech

Average Grade

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

Add a method that returns the average of a student's grades, exactly the kind of summary computation Enumerable was built for.

Watch out for two edge cases: the student doesn't exist, and the student has no grades yet.

challenge icon

Challenge

Easy

Add a method average_grade(name) that:

  1. Prints Student '<name>' not found. and returns nil if the name doesn't exist.
  2. Returns 0 if the student exists but has no grades.
  3. Otherwise returns the arithmetic mean of :grades as a Float.

Replace the test block with:

add_student("Alice", 20, ["Math"])
add_student("Bob",   22, ["Biology"])
add_grade("Alice", 90)
add_grade("Alice", 80)
puts average_grade("Alice")
puts average_grade("Bob")
puts average_grade("Charlie").inspect

Expected output:

Student 'Alice' added.
Student 'Bob' added.
Grade 90 added for 'Alice'.
Grade 80 added for 'Alice'.
85.0
0
Student 'Charlie' not found.
nil

Cheat sheet

Handle edge cases when computing averages from a collection:

def average_grade(name)
  student = @students.find { |s| s[:name] == name }
  if student.nil?
    puts "Student '#{name}' not found."
    return nil
  end
  grades = student[:grades]
  return 0 if grades.empty?
  grades.sum.to_f / grades.size
end
  • Use .find to locate a record; returns nil if not found.
  • Guard against an empty collection with .empty? before dividing.
  • Use .to_f on the sum (or size) to ensure a Float result.

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

# TODO: def average_grade(name), handles missing student, empty grades, returns Float average

add_student("Alice", 20, ["Math"])
add_student("Bob",   22, ["Biology"])
add_grade("Alice", 90)
add_grade("Alice", 80)
puts average_grade("Alice")
puts average_grade("Bob")
puts average_grade("Charlie").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