Last active
February 26, 2016 02:57
-
-
Save nurey/6368fd305fe78adc46cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# this requires ruby 2.3 | |
students = { | |
:"bobby crimble" => { | |
math: 68, | |
physics: 77, | |
phys_ed: 81, | |
english: 71 | |
}, | |
:"anne shirley" => { | |
math: 69, | |
physics: 76, | |
phys_ed: 99, | |
english: 87 | |
} | |
} | |
# transform students to: | |
# [ | |
# { math: "anne shirley" }, | |
# { physics: "bobby crimble" }, | |
# { phys_ed: "anne shirley" }, | |
# { english: "anne shirley" } | |
# ] | |
top_student_for_subject = {} # intermediate hash to accumulate highest grade and name for a subject | |
students.each do |name, report| | |
report.each do |subject, grade| | |
top_grade = top_student_for_subject.dig(subject, :grade) || 0 | |
top_student_for_subject[subject] = { name: name, grade: grade } if grade > top_grade | |
end | |
end | |
subjects = [] # the final array of hashes | |
top_student_for_subject.each do |subject, student| | |
subjects << { subject => student[:name] } | |
end | |
puts subjects |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment