Menu
CoddyTech

Liệt kê theo khóa học

Thuộc phần Logic và luồng xử lý trong hành trình Ruby của Coddy. Bài học 52 trên 56.

Thêm một phương thức tìm tất cả học viên đăng ký khóa học được chỉ định và trả về tên của họ dưới dạng một mảng. Đây là kiểu kết hợp select/map mà bạn đã luyện tập.

challenge icon

Thử thách

Dễ

Thêm phương thức list_by_course(course) để trả về một mảng tên của những học sinh có mảng :courses chứa course. Tên phải xuất hiện theo thứ tự được thêm vào; nếu không có học sinh nào đăng ký, hãy trả về [].

Thay khối test bằng:

add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob",   22, ["Biology", "Math"])
add_student("Cara",  19, ["Physics"])
puts list_by_course("Math").inspect
puts list_by_course("Physics").inspect
puts list_by_course("Art").inspect

Đầu ra mong đợi:

Student 'Alice' added.
Student 'Bob' added.
Student 'Cara' added.
["Alice", "Bob"]
["Alice", "Cara"]
[]

Tự làm thử

$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

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

def average_grade(name)
  unless $student_records.key?(name)
    puts "Student '#{name}' not found."
    return nil
  end
  grades = $student_records[name][:grades]
  return 0 if grades.empty?
  grades.sum.to_f / grades.length
end

# TODO: def list_by_course(course), trả về mảng (array) gồm tên những học sinh đăng ký `course`

add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob",   22, ["Biology", "Math"])
add_student("Cara",  19, ["Physics"])
puts list_by_course("Math").inspect
puts list_by_course("Physics").inspect
puts list_by_course("Art").inspect
quiz iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong Logic và luồng xử lý

Tự luyện tập: Trình biên dịch Ruby online