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?

2
  • probably best not to call your array h since this is usually reserved for hashes. Commented Jul 13, 2016 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 "How to Ask" including the linked pages, and "minimal reproducible example". Commented Jul 13, 2016 at 22:20

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.