How do I sort an array of hashes by a value in Ruby?
Still on my client app. I have a list of orders as an array of hashes and the client wants them shown from the biggest total to the smallest. In irb:
Cite
Poignant Guide Ruby Q&A, "How do I sort an array of hashes by a value in Ruby?", https://poignantguide.net/answers/read/how-do-i-sort-an-array-of-hashes-by-a-value-in-ruby/, accessed 2026-12-02.orders = [ { id: 1, customer: "Ada", total: 40 }, { id: 2, customer: "Chidi", total: 15 }, { id: 3, customer: "Bola", total: 40 } ] orders.sort orders.sort_by(:total)Both lines fail:
comparison of Hash with Hash failed (ArgumentError) wrong number of arguments (given 1, expected 0) (ArgumentError)In the Rails console I would write
Order.order(:total)and it just works, so I assumedsort_by(:total)would be the Ruby version of that. I am on Ruby 3.3.How do I sort by the
:totalvalue, how do I flip it to biggest first, and what do I do when two orders have the same total (Ada and Bola both have 40)? I would like the customer name to break the tie.
Write something first.
Give people something to work with: at least 30 words on what happened and what you tried.
That is too long. Keep it under 6,000 characters.
Write the question as the title, 15 to 140 characters, no links.
Pick a category.
Add a name (2 to 40 characters, no links).
That email address does not look right.
That was quick. Read the thread, then try again.
The form expired. Reload the page and post again.
Something went wrong with the form. Reload and try again.
Please complete the check and post again.
Limit reached for now. Try again later.
This thread is closed to new replies.
This thread no longer accepts replies.
Something went wrong with the form. Reload and try again.
Post a reply or question first (name and email), then this browser can vote, edit and accept answers.
You cannot vote on your own post.
Only the author (within 30 days) or the forum team can do that.
That email already has an account. Use your sign-in link instead.
New accounts are paused for the moment. Try again later.
That was already posted.