Add Student
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 49 of 56.
Define an add_student method that registers a new student in the shared student_records hash.
Refusing duplicates is the only branch, once a student exists, report it and return without overwriting.
Challenge
EasyAt the top of your file, keep student_records = {}. Then define a method add_student(name, age, courses) that:
- If
nameis already a key instudent_records, printsStudent '<name>' already exists.and returns. - Otherwise stores
{ age: age, grades: [], courses: courses }undernameand printsStudent '<name>' added.
At the bottom of your file, replace the test block with:
add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Biology", "Chemistry"])
add_student("Alice", 21, ["Art"])
puts student_records.inspectThe expected output is:
Student 'Alice' added.
Student 'Bob' added.
Student 'Alice' already exists.
{"Alice"=>{:age=>20, :grades=>[], :courses=>["Math", "Physics"]}, "Bob"=>{:age=>22, :grades=>[], :courses=>["Biology", "Chemistry"]}}Because methods can't see local variables from the enclosing script, declare student_records with $student_records (a global) so the method can read and update it. Use that name inside the method too.
Cheat sheet
Use a global variable ($variable_name) so methods can access and modify variables defined outside their scope:
$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."
endKey points:
- Prefix with
$to make a variable global (accessible inside methods) - Use
.key?(name)to check if a hash already contains a key - Use
returnto exit a method early after handling a duplicate
Try it yourself
$student_records = {}
# TODO: def add_student(name, age, courses), guard against duplicates,
# store { age:, grades: [], courses: }, print added/already exists
add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Biology", "Chemistry"])
add_student("Alice", 21, ["Art"])
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