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

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