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)
Check viewARU - Brand Newsletter!
Newsletter to DEVs by DEVs β boost your Personal Brand & career! π