0

This is my input hash:

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

I need the result to be sorted in descending order of 'bookings_nd' rather than 'user_id'. I want it to look like this:

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

How to do it?

Zain Asif
  • 217
  • 2
  • 13
Hugo Barthelemy
  • 129
  • 1
  • 11
  • probably best not to call your array `h` since this is usually reserved for hashes. – Sagar Pandya Jul 13 '16 at 22:11
  • 2
    We'd like to see your effort toward solving the problem. Without that it looks like you want us to write your code. Please read "[ask]" including the linked pages, and "[mcve]". – the Tin Man Jul 13 '16 at 22:20

1 Answers1

14

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

Community
  • 1
  • 1
Ilya Lavrov
  • 2,810
  • 3
  • 20
  • 37