Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the highest value in an array of hashes in Ruby

Tags:

arrays

ruby

hash

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"
    }
]
like image 551
AliZ Avatar asked Sep 19 '16 20:09

AliZ


People also ask

How do you find the largest number in an array in Ruby?

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.

Do hashes have indexes Ruby?

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.

What is the difference between Hash and array in Ruby?

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.

Can you map a Hash in Ruby?

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.


1 Answers

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"
like image 192
Bartłomiej Gładys Avatar answered Sep 18 '22 07:09

Bartłomiej Gładys