List By Course
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 52 of 56.
Add a method that finds every student enrolled in a given course and returns their names as an array. This is the kind of select/map chain you've already practiced.
Challenge
EasyAdd a method list_by_course(course) that returns an array of names of students whose :courses array includes course. Names should appear in insertion order; if no one is enrolled, return [].
Replace the test block with:
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").inspectExpected output:
Student 'Alice' added.
Student 'Bob' added.
Student 'Cara' added.
["Alice", "Bob"]
["Alice", "Cara"]
[]Cheat sheet
Use select + map to filter students by a field and return names:
def list_by_course(course)
@students.select { |s| s[:courses].include?(course) }
.map { |s| s[:name] }
endTry it yourself
$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), return array of names enrolled in `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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier