Ruby On Rails: How can I sort this hash by its keys in descending order
(rdb:60) p resultsHash
{ 1 => [#<Participant id: 6, username: "player2", online_rank: 7, created_at: "2011-05-14 04:49:22", updated_at: "2011-05-14 04:57:56", win_count: 1, device_type: "iPad">],
0 => [#<Participant id: 5, username: 开发者_开发百科"player1", online_rank: 3, created_at: "2011-05-12 02:47:50", updated_at: "2011-05-12 02:47:50", win_count: 0, device_type: "iPad">,
#<Participant id: 4, username: "iPhone4Simulator", online_rank: 4, created_at: "2011-05-12 02:45:37", updated_at: "2011-05-12 02:45:37", win_count: 0, device_type: "iPad">]}
I've tried...
resultsHash.sort {|a,b| -(a[0]<=>b[0])}
but the results aren't sorted by the keys when I iterate through the hash using each_pair
.
Thanks!
What you really want to do is add an ORDER BY clause to your query. If this is Rails 3, Participant.order(:id).all
is one way to do it.
To answer your immediate question, though, you would say resultsHash.sort_by(&:id)
. But don't do it this way.
Side note, use snake_case for Ruby code, not camelCase.
Edit: See comments.
resultsHash.sort.reverse
Note that it'll return an Array of [key, value]
pairs. But you can still iterate like with a Hash:
resultsHash.sort.reverse.each do |key, value|
....
end
Or you can retrieve only the values: resultsHash.sort.reverse.map { |key, value| value }
, or resultsHash.sort.reverse.map(&:last)
I realize this is an old question, but one way you can do exactly what you want while still retaining a return type of Hash
is to use .slice
on the sorted keys:
resultHash.slice(*resultHash.keys.sort)
精彩评论