Hugo Barthelemy Hugo Barthelemy - 1 year ago 79
Ruby Question

Sort array of hash by key, return descending order in Ruby

My input hash:

h = [{user_id: 1, bookings_nd: 3}, {user_id: 2, bookings_nd: 10}, {user_id: 3, bookings_nd: 2}]

I need
h = [{user_id: 2, bookings_nd: 10}, {user_id: 1, bookings_nd: 3}, {user_id: 3, bookings_nd: 2}]

How to do ?
Thank you

Answer Source

You can do

h.sort_by! { |k| -k[:bookings_nd] }


h.sort_by! { |k| k[:bookings_nd] }.reverse!

Also i guess this question is duplicate for Sorting an array in descending order in Ruby

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download