What is the most efficient way to sort hashes in ruby? -
i trying sort 20 hashes in ruby based on 1 of attributes of array. want return top 3 hash keys, don't want have compare each one.
here example below of similar trying sort. want sort based on 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}]
for this, want array ["joey", "green", "board"]. suggestions on how tackle issue?
edit: here example in original hash form:
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} }
assuming powerrankings
not showed rather,
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} }
then,
powerrankings.sort_by{|_, h| h[:powerrank]}.reverse.first(3).map(&:first) # => ["joey", "green", "board"]
Comments
Post a Comment