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"
}
]
The array. max() method in Ruby enables us to find the maximum value among elements of an array. It returns the element with the maximum value.
In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type.
Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements.
Map is a Ruby method that you can use with Arrays, Hashes & Ranges. The main use for map is to TRANSFORM data. For example: Given an array of strings, you could go over every string & make every character UPPERCASE.
You can use max_by
method
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With