【问题标题】:Find the highest value in an array of hashes in Ruby在 Ruby 中查找哈希数组中的最大值
【发布时间】:2016-09-19 20:16:48
【问题描述】:

我有一个由几个哈希组成的数组。我想找到特定键/值的最大值并打印该哈希的名称值。例如,我有一个“学生”哈希数组,其中包含每个学生的信息。我想找出哪个学生的考试成绩最高并打印出他们的名字。对于下面的数组,“Kate Saunders”的测试分数最高,所以我想打印出她的名字。

任何帮助或指针都将不胜感激。我现在有一个 hacky 工作,但我知道有更好的方法。我是 Ruby 的新手并且很喜欢它,但在这个问题上遇到了困难。非常感谢!!!

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"
    }
]

【问题讨论】:

  • 1.你都尝试了些什么? 2. 你已经拥有的 hacky 方式是什么?添加相同的代码。
  • 我的 hacky 方法是将测试分数推送到一个单独的数组中,并获取最高索引并将其与学生数组中的哈希索引进行比较。太丑了。

标签: arrays ruby hash


【解决方案1】:

你可以使用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"

【讨论】:

    【解决方案2】:
    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
    

    Ima 的父亲是 James ("Big Jim") Hogg,1891 年至 1895 年间担任得克萨斯州州长。Ima 有一个名叫“Ura”的妹妹(我认为这是事实),结果证明这是都市传说。

    【讨论】:

    • 谢谢卡里!刚看到你上面的评论。对不起!仍在学习如何使用 Stack Overflow 的礼仪。所以,我跳到了第一个有效的答案——初学者的错误。感谢您的解决方案。这是一个不错的选择,可以完成工作!
    猜你喜欢
    • 1970-01-01
    • 2015-07-23
    • 2018-01-31
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 2018-04-07
    • 1970-01-01
    相关资源
    最近更新 更多