AliZ AliZ - 2 months ago 7
Ruby Question

Find the highest value in an array of hashes in Ruby

I have an array made of several hashes. I would like to find the highest value for a specific key/value and print the name value for that hash. For example, I have a "student" array of hashes containing information to each student. I would like to find which student had the highest test score and print their name out. For the array below, "Kate Saunders" has the highest test score, so I would like to print out her name.

Any help or pointers were to start on this would be greatly appreciated. I have a hacky work around right now, but I know there's a better way. I'm new to Ruby and loving it, but stumped on this one. Thanks so much!!!

students = [
{
name: "Mary Jones",
test_score: 80,
sport: "soccer"
},
{
name: "Bob Kelly",
test_score: 95,
sport: "basketball"
}.
{
name: "Kate Saunders",
test_score: 99,
sport: "hockey"
},
{
name: "Pete Dunst",
test_score: 88,
sport: "football"
}
]

Answer

You can use max_bymethod

students = [ { name: "Mary Jones", test_score: 80, sport: "soccer" }, { name: "Bob Kelly", test_score: 95, sport: "basketball" }, { name: "Kate Saunders", test_score: 99, sport: "hockey" }, { name: "Pete Dunst", test_score: 88, sport: "football" } ]

students.max_by{|k| k[:test_score] }
#=> {:name=>"Kate Saunders", :test_score=>99, :sport=>"hockey"}

students.max_by{|k| k[:test_score] }[:name]
#=> "Kate Saunders"