开发者

Wanting to sort a hash in ruby by value first, and key second [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Sorting a hash i开发者_JS百科n Ruby by its value first then its key.

I need to order a hash so that the value is the first priority, and then when the values are the same it orders by the key.

I am currently sorting using this code, but I don't see how to do sort_by with a second element.

Hash[@card_value_counts.sort_by{|k, v| k * -1}]

Examples of what I'm looking for would be:

pre_sorted = {10=>1, 9=>2, 3=>2, 2=>1, 1=>1}
sorted = {9=>2, 3=>2, 10=>1, 2=>1, 1=>1}

pre_sorted = {12=>2, 10=>3, 9=>4, 5=>3}
sorted = {9=>4, 10=>3, 5=>3, 12=>2}


Array has a cool feature: comparing two arrays with the <=> method will compare them element-by-element. You can exploit this for multi-value sorting:

sorted_hash = Hash[original_hash.sort_by { |k,v| [-1 * v, -1 * k] }]

UPDATE: Maybe you know this already, but I assumed you're using Ruby 1.9. In earlier versions, Hashes are not guaranteed to maintain their order.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜