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.
Sfida
FacileAggiungi 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").inspectOutput 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
Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.
Tutte le lezioni di Logica e flusso
1Le stringhe in dettaglio
Panoramica dei metodi delle stringheInterpolazione di stringheIterare sulle stringheDividere e unireRiepilogo - Tessitore di stringhe4Blocchi, Proc e Lambda
Che cos’è un Block?do..end vs parentesi graffeLa keyword yieldParametri del BlockProc e LambdaRiepilogo - Iteratore personalizzato7Hash in Ruby - Parte 2
Hash.new con valori predefinitiIterare sugli hashHash annidatiUnire e trasformareRipasso - Contatore di frequenza10Progetto - Registri degli studenti
Panoramica del progettoAggiungere uno studente2Intervalli
Che cos'è un intervallo?Metodi degli intervalliIntervalli in Case / WhenRiepilogo - Esercitarsi con gli intervalli5La potenza di Enumerable
Select e RejectConcatenare MapReduce / Injectcount, all?, any?, none?group_by e partitionsort_by, min_by, max_byRiepilogo - Pipeline di datiEsercitati da solo: Compilatore Ruby online