Find the largest value in a hash array in Ruby

I have an array of several hashes. I would like to find the highest value for a particular key / value and print the name value for this hash. For example, I have a “student” hash array containing information for each student. I would like to find which student had the highest test score and type in my name. For the array below, Kate Saunders has the highest test score, so I would like to print her name.

Any help or pointers should have started with this would be very helpful. Now I have a hacker job, but I know that there is a better way. I am new to Ruby and love it, but at a dead end. Many thanks!

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"
    }
]
+4
2

max_by

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"
+7
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" },
             { name: "Ima Hogg", test_score: 99, sport: "darts" }
           ]

ala @Bartek.

max_score = students.max_by { |h| h[:test_score] }[:test_score]
  #=> 99 

, () .

star_students = students.select { |h| h[:test_score] == max_score }.
                         map { |h| h[:name] }
  #=> ["Kate Saunders", "Ima Hogg"] 

puts star_students
  # Kate Saunders
  # Ima Hogg

( " " ) , 1891 1895 . "" "(, , ), .

+1

Source: https://habr.com/ru/post/1655122/


All Articles