Menu
CoddyTech

학생 추가

Coddy Ruby 여정의 로직과 흐름 섹션에 포함된 레슨. 56개 중 49번째.

공유 student_records 해시에 새 학생을 등록하는 add_student 메서드를 정의하세요.

중복을 거부하는 것이 유일한 분기입니다. 학생이 이미 존재하면 이를 알리고 덮어쓰지 않은 채 반환하세요.

challenge icon

챌린지

쉬움

파일 맨 위에 student_records = {}를 그대로 둡니다. 그런 다음 다음과 같은 메서드 add_student(name, age, courses)를 정의합니다.

  1. name이 이미 student_records의 키라면 Student '<name>' already exists.를 출력하고 반환합니다.
  2. 그렇지 않으면 { age: age, grades: [], courses: courses }를 name 아래에 저장하고 Student '<name>' added.를 출력합니다.

파일 맨 아래에서 테스트 블록을 다음 내용으로 바꿉니다.

add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Biology", "Chemistry"])
add_student("Alice", 21, ["Art"])
puts student_records.inspect

예상 출력은 다음과 같습니다.

Student 'Alice' added.
Student 'Bob' added.
Student 'Alice' already exists.
{"Alice"=>{:age=>20, :grades=>[], :courses=>["Math", "Physics"]}, "Bob"=>{:age=>22, :grades=>[], :courses=>["Biology", "Chemistry"]}}

메서드는 바깥 스크립트의 지역 변수를 볼 수 없으므로, 메서드에서 변수를 읽고 업데이트할 수 있도록 student_records를 전역 변수인 $student_records로 선언합니다. 메서드 안에서도 이 이름을 사용합니다.

직접 해보기

$student_records = {}

# TODO: def add_student(name, age, courses)를 정의하고, 중복을 방지하고,
# { age:, grades: [], courses: }를 저장하고, 추가됨/이미 존재함을 출력

add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Biology", "Chemistry"])
add_student("Alice", 21, ["Art"])
puts $student_records.inspect
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

로직과 흐름의 모든 레슨

직접 연습해 보세요: 온라인 Ruby 컴파일러