/ Tags: RUBY-CODE / Categories: SOLUTIONS

Sort An Array Of Hashes By Multiple Keys In Ruby

Sorting a collection of hashes by a single key is straightforward, but sorting by multiple keys — primary sort by one field, secondary sort by another — requires a slightly different approach using Ruby’s sort_by with an array of values.

Description

Ruby’s Enumerable#sort_by accepts an array as the sort key. Ruby compares arrays element by element, so [primary, secondary] sorts by primary first, then by secondary only when primary values are equal. This works for any number of sort keys and supports ascending and descending order per key using negation or reverse. This is commonly needed when displaying sorted records — e.g., sort by status first, then by name alphabetically within each status group.

Sample input:

  records = [
    { name: "Charlie", score: 90, level: 2 },
    { name: "Alice",   score: 90, level: 1 },
    { name: "Bob",     score: 85, level: 3 },
    { name: "Diana",   score: 85, level: 1 }
  ]


Sample Output (sort by score desc, then name asc):

  [
    { name: "Alice",   score: 90, level: 1 },
    { name: "Charlie", score: 90, level: 2 },
    { name: "Bob",     score: 85, level: 3 },
    { name: "Diana",   score: 85, level: 1 }
  ]

Answer

  # Sort by score descending, then name ascending
  sorted = records.sort_by { |r| [-r[:score], r[:name]] }

  # Sort by multiple keys in a reusable method
  def multi_sort(array, *keys)
    array.sort_by { |item| keys.map { |key, dir| dir == :desc ? -item[key] : item[key] rescue item[key] } }
  end

  # Example: sort by score desc, then level asc
  sorted = records.sort_by { |r| [-r[:score], r[:level], r[:name]] }

Learn More

cdrrazan

Rajan Bhattarai

Full Stack Software Developer! 💻 🏡 Grad. Student, MCS. 🎓 Class of '23. GitKraken Ambassador 🇳🇵 2021/22. Works with Ruby / Rails. Photography when no coding. Also tweets a lot at TW / @cdrrazan!

Read More