1

I have an array of hash like this:

[{683=>5}, {689=>2}, {692=>10}]

I want the result like this:

[{692=>10}, {683=>5}, {689=>2}]

Could any one help me?

1 Answer 1

4

Use Enumerable#sort_by. The return value of the block is used as comparison key.

[{683=>5}, {689=>2}, {692=>10}].sort_by { |h| -h.values[0] }
# => [{692=>10}, {683=>5}, {689=>2}]
Sign up to request clarification or add additional context in comments.

5 Comments

Try sort_by { |h| h.values[0] }.reverse!, surprisingly it is slighlty faster and a little clearer, IMHO.
@toro2k, I just tried it with fruity in Windows 7 64bit, ruby 2.0. It says both are similar.
On my Debian box fruity reports a 10% difference, well, it seems to be just a little clearer... :-)
It looks like reverse is faster by 10% for me as well (on osx). I had an array of 10,000 hashes and ran each test 100 times in fruity.
@toro2k, I got it. Both decorate(in decorate-sort-undecorate), reverse! take O(n) times. But decorate is performed in ruby loop, while reverse! is performed in C. More operations in the block means caused visible time difference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.