Menu
Coddy logo textTech

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 icon

Challenge

Easy

At the top of your file, keep student_records = {}. Then define a method add_student(name, age, courses) that:

  1. If name is already a key in student_records, prints Student '<name>' already exists. and returns.
  2. Otherwise stores { age: age, grades: [], courses: courses } under name and prints Student '<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.inspect

The 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."
end

Key points:

  • Prefix with $ to make a variable global (accessible inside methods)
  • Use .key?(name) to check if a hash already contains a key
  • Use return to 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow