哈希的Ruby排序哈希

时间:2015-01-23 05:28:29

标签: ruby

我有一系列活动,我想根据平均评分和活动评分次数进行排序。

activities = {
  :one => { :avg_rating => 5, :total_ratings => 23 },
  :two => { :avg_rating => 5, :total_ratings => 18 },
  :three => { :avg_rating => 5, :total_ratings => 54 }
}

编辑 - 更新了所以我期待的结果是正确的

排序的结果将按:three, :one, :two

的顺序排列

谢谢!

1 个答案:

答案 0 :(得分:0)

activities.sort_by { |k,v| 
  [v[:avg_rating], v[:total_ratings]] 
}.reverse

是否只需要元素名称:

activities.sort_by { |k,v| 
  [v[:avg_rating], v[:total_ratings]]
}.reverse.map &:first
#⇒ [
#  [0] :three,
#  [1] :one,
#  [2] :two
#]