# How do I sort an array of hashes by a value in Ruby?

Source: https://poignantguide.net/answers/read/how-do-i-sort-an-array-of-hashes-by-a-value-in-ruby/
Site: Poignant Guide Ruby Q&A, category Arrays, hashes and Enumerable
Published: 2026-12-01. Updated: 2026-12-01. Replies: 2.

## Question by Ngozi A., 2026-12-01

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:

```ruby
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 assumed `sort_by(:total)` would be the Ruby version of that. I am on Ruby 3.3.

How do I sort by the `:total` value, 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.

## Reply 1 by Sunita R., 2026-12-01

In Python this is `sorted(orders, key=lambda o: o["total"])`. In Ruby I think the shape is the same: the thing you pass tells Ruby what to compare. I used `sort_by { |o| o[:total] }` in a script last week and it did what I wanted.

## Reply 2 by Kai N., 2026-12-01

`orders.sort_by(&:total)` is the tidy way, symbol to proc, and I use it everywhere in our code. Add `.reverse` for biggest first. That is all you need for the report, in my experience.

---
Cite as: 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.
