Skip to content
Poignant Guide Ruby Q&A

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

Asked by Ngozi A. · Arrays, hashes and Enumerable2 repliesupdated

Short answer

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:

Written by Ngozi A. ·
CitePoignant 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.
  1. Member ·
    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.

    0
    ReplyLink

Plain text or simple Markdown. Links are nofollow. Your email is never shown.

  1. Sunita R.Member ·

    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.

  2. Kai N.Member ·

    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.

Poignant Guide Ruby Q&A. Questions and answers on learning Ruby and programming: syntax, blocks, objects, gems, Rails, debugging and reading the Poignant Guide.