Convert An Array Of Single Key Hashes Into An Attribute Hash
You may encounter a situation where you have an array of single-key hashes and need to restructure it into a grouped hash based on the keys.
Description
This Ruby method demonstrates an elegant and concise way to do that using each_with_object
and Hash
initialization. It transforms an array of hashes—each containing a single key-value pair—into a grouped hash where each key maps to an array of its corresponding values. It uses each_with_object({})
to accumulate the result in a clean and efficient way.
The key part is item.shift
, which destructures the first (and only) key-value pair from each hash. Then, (hsh[k] ||= []) << v
appends the value to the correct key in the output hash.
This is especially useful when dealing with normalized inputs or parameter arrays in APIs or forms.
Sample input:
input = [
{ foo: 1 },
{ bar: 2 },
{ foo: 3 },
{ bar: 4 },
{ baz: 5 }
]
Sample Output:
{
foo: [1, 3],
bar: [2, 4],
baz: [5]
}
Answer
def convert_to_attr_hash(arr_with_hashes)
arr_with_hashes.each_with_object({}) do |item, hsh|
k, v = item.shift
(hsh[k] ||= []) << v
end
end
Check viewARU - Brand Newsletter!
Newsletter to DEVs by DEVs — boost your Personal Brand & career! 🚀