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
EasyAdd a method average_grade(name) that:
- Prints
Student '<name>' not found.and returnsnilif the name doesn't exist. - Returns
0if the student exists but has no grades. - Otherwise returns the arithmetic mean of
:gradesas 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").inspectExpected output:
Student 'Alice' added.
Student 'Bob' added.
Grade 90 added for 'Alice'.
Grade 80 added for 'Alice'.
85.0
0
Student 'Charlie' not found.
nilCheat 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
.findto locate a record; returnsnilif not found. - Guard against an empty collection with
.empty?before dividing. - Use
.to_fon 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier