Menu
Coddy logo textTech

Add Grade

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

Now extend the system with an add_grade method. It appends a numeric grade to the student's :grades array, as long as the student exists.

If the name isn't in the records, report that and bail out.

challenge icon

Challenge

Easy

Keep your $student_records hash and add_student from the previous lesson. Add a method add_grade(name, grade) that:

  1. Prints Student '<name>' not found. if the name doesn't exist, and returns.
  2. Otherwise pushes grade into the student's :grades array and prints Grade <grade> added for '<name>'.

Replace the test block at the bottom with:

add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Biology", "Chemistry"])
add_grade("Alice", 90)
add_grade("Alice", 85)
add_grade("Bob", 75)
add_grade("Charlie", 80)
puts $student_records.inspect

Expected output:

Student 'Alice' added.
Student 'Bob' added.
Grade 90 added for 'Alice'.
Grade 85 added for 'Alice'.
Grade 75 added for 'Bob'.
Student 'Charlie' not found.
{"Alice"=>{:age=>20, :grades=>[90, 85], :courses=>["Math", "Physics"]}, "Bob"=>{:age=>22, :grades=>[75], :courses=>["Biology", "Chemistry"]}}

Cheat sheet

Add an add_grade(name, grade) method that checks existence, then appends to :grades:

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

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

# TODO: def add_grade(name, grade)

add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Biology", "Chemistry"])
add_grade("Alice", 90)
add_grade("Alice", 85)
add_grade("Bob", 75)
add_grade("Charlie", 80)
puts $student_records.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