/ Tags: RUBY-CODE / Categories: SOLUTIONS

Group Array Elements By Multiple Attributes In Ruby

Grouping records by a single attribute is straightforward using Enumerable#group_by. But what if you want to group by multiple attributes, such as categorizing records by both type and status? This method handles that need elegantly.

Description

Sometimes you need to group an array of hashes (like ActiveRecord results or JSON data) by composite keys, such as [:category, :status]. Ruby’s group_by doesn’t support grouping by multiple keys out of the box, but you can easily extend its behavior. This solution builds a composite key using an array of the desired attributes, allowing you to nest and group your data naturally.

Sample input:

  records = [
    { category: "books", status: "published", title: "Ruby Basics" },
    { category: "books", status: "draft", title: "Rails 8 Guide" },
    { category: "videos", status: "published", title: "Ruby Conf Talk" },
    { category: "books", status: "published", title: "Metaprogramming" }
  ]


Sample Output:

  {
    ["books", "published"] => [
      { category: "books", status: "published", title: "Ruby Basics" },
      { category: "books", status: "published", title: "Metaprogramming" }
    ],
    ["books", "draft"] => [
      { category: "books", status: "draft", title: "Rails 8 Guide" }
    ],
    ["videos", "published"] => [
      { category: "videos", status: "published", title: "Ruby Conf Talk" }
    ]
  }

Answer

  def group_by_keys(array, *keys)
    array.group_by do |item|
    keys.map { |key| item[key] }
  end
end

# Example usage:
# group_by_keys(records, :category, :status)

Learn More

cdrrazan

Rajan Bhattarai

Software Engineer by work! πŸ’» 🏑 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