sunil
sunil

Reputation: 1040

Sort array of hash in ruby

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?

Upvotes: 1

Views: 157

Answers (1)

falsetru
falsetru

Reputation: 369444

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}]

Upvotes: 4

Related Questions