gpt4 book ai didi

ruby - 如何根据散列中的值从数组中获取散列?

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:41 25 4
gpt4 key购买 nike

如何根据散列中的值从数组中获取散列?在这种情况下,我想选择得分最低的散列,即 potato。我使用 Ruby 1.9。

[
{ name: "tomato", score: 9 },
{ name: "potato", score: 3 },
{ name: "carrot", score: 6 }
]

最佳答案

可以使用Enumerable的min_by方法:

ary.min_by {|h| h[:score] } 
#=> { name: "potato", score: "3" }

关于ruby - 如何根据散列中的值从数组中获取散列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17553749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com