我试图根据数组的一个属性在ruby中排序大约20个哈希值。我想只返回前三个哈希键,但我不想比较每一个。
下面是一个类似于我尝试排序的示例。我想根据powerrank进行排序。
["green", {:price=>24.88, :numreviews=>822, :avgStarsRank=>41.0, :reviewsrank=>28, :powerrank=>73.976}]
["steve", {:price=>14.96, :numreviews=>3, :avgStarsRank=>40.0, :reviewsrank=>0, :powerrank=>42.992000000000004}]
["joey", {:price=>40.27, :numreviews=>814, :avgStarsRank=>44.0, :reviewsrank=>28, :powerrank=>80.054}]
["board", {:price=>14.96, :numreviews=>3, :avgStarsRank=>40.0, :reviewsrank=>0, :powerrank=>47}]
["john", {:price=>40.27, :numreviews=>814, :avgStarsRank=>44.0, :reviewsrank=>28, :powerrank=>16}]
为此,我想要的所有内容都是[" joey"," green"," board"]。关于如何解决这个问题的任何建议?
编辑:以下是原始哈希表单中的示例:
powerrankings =
{
"green"=>{:price=>24.88, :numreviews=>822, :avgStarsRank=>41.0, :reviewsrank=>28, :powerrank=>73.976},
"steve"=>{:price=>14.96, :numreviews=>3, :avgStarsRank=>40.0, :reviewsrank=>0, :powerrank=>42.992000000000004},
"joey"=>{:price=>40.27, :numreviews=>814, :avgStarsRank=>44.0, :reviewsrank=>28, :powerrank=>80.054}}
"board"=>{:price=>14.96, :numreviews=>3, :avgStarsRank=>40.0, :reviewsrank=>0, :powerrank=>47},
"john"=>{:price=>40.27, :numreviews=>814, :avgStarsRank=>44.0, :reviewsrank=>28, :powerrank=>16}
}
答案 0 :(得分:3)
假设powerrankings
不是你所展示的,而是
powerrankings = {
"green" => {:price=>24.88, :numreviews=>822, :avgStarsRank=>41.0, :reviewsrank=>28, :powerrank=>73.976},
"steve" => {:price=>14.96, :numreviews=>3, :avgStarsRank=>40.0, :reviewsrank=>0, :powerrank=>42.992000000000004},
"joey" => {:price=>40.27, :numreviews=>814, :avgStarsRank=>44.0, :reviewsrank=>28, :powerrank=>80.054},
"board" => {:price=>14.96, :numreviews=>3, :avgStarsRank=>40.0, :reviewsrank=>0, :powerrank=>47},
"john" => {:price=>40.27, :numreviews=>814, :avgStarsRank=>44.0, :reviewsrank=>28, :powerrank=>16}
}
然后,
powerrankings.sort_by{|_, h| h[:powerrank]}.reverse.first(3).map(&:first)
# => ["joey", "green", "board"]