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
EasyKeep your $student_records hash and add_student from the previous lesson. Add a method add_grade(name, grade) that:
- Prints
Student '<name>' not found.if the name doesn't exist, and returns. - Otherwise pushes
gradeinto the student's:gradesarray and printsGrade <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.inspectExpected 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}'."
endTry 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
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