我按照下面列出的顺序制作哈希,并按升序排序,但是当我想按降序排序时,我得不到正确的结果。
Hash就是这个
hash_answers = {}
unless answers.blank?
answers.each_with_index do |ans, index|
voted_up_users = ans.votes_up_by_all_users(ans)
voted_down_users = ans.votes_down_by_all_users(ans)
hash_answers[ans.id] = {
:id => ans.id,
:count => voted_up_users.count - voted_down_users.count,
:created_at => ans.created_at
}
end
end
当我按created_at
和按基数
answers = hash_answers.sort_by { |k, v| [ v[:count] , v[:created_at] ] }
但如何按created_at
降序排序,并按计数排序。
如果有人可以提供帮助 感谢
答案 0 :(得分:0)
你可以在排序方法中使用block,在块中你应该提供排序规则,在你的情况下它可能是这样的:
temp = hash_answers.sort do |h1,h2|
v1 = h1.last; v2 = h2.last
[v2[:count],v2[:created_at]] <=> [v1[:count],v1[:created_at]]
end
answer = Hash[temp]