Hugo Barthelemy Hugo Barthelemy - 4 months ago 10
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

You can do

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

or

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

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

Comments