Skip to content

Instantly share code, notes, and snippets.

@nurey
Last active February 26, 2016 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nurey/6368fd305fe78adc46cc to your computer and use it in GitHub Desktop.
Save nurey/6368fd305fe78adc46cc to your computer and use it in GitHub Desktop.
# 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