Menu
Coddy logo textTech

Elenco per corso

Fa parte della sezione Logica e flusso del percorso Ruby di Coddy. Lezione 52 di 56.

Aggiungi un metodo che trovi tutti gli studenti iscritti a un determinato corso e restituisca i loro nomi come array. Questo è il tipo di catena select/map che hai già esercitato.

challenge icon

Sfida

Facile

Aggiungi un metodo list_by_course(course) che restituisca un array di nomi degli studenti il cui array :courses include course. I nomi devono apparire nell’ordine di inserimento; se nessuno è iscritto, restituisci [].

Sostituisci il blocco di test con:

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

Output previsto:

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

Provalo tu

$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), restituisci un array di nomi degli studenti iscritti a `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 iconMettiti alla prova

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore Ruby online