Reputation: 6674
If I have an array of ActiveRecord objects and want to combine them by attribute, how might I do that?
Example:
x = [#<Foo id: 1, a: 2, b: 3>, #<Foo id: 2, a:20, b:30>, #<Foo id: 3, a: 200, b: 300>]
and I want:
{id: [1, 2, 3], a: [2, 20, 200], b: [3, 30, 300]}
Upvotes: 0
Views: 44
Reputation: 15515
Quick and dirty:
x = [#<Foo id: 1, a: 2, b: 3>, #<Foo id: 2, a:20, b:30>, #<Foo id: 3, a: 200, b: 300>]
result = {id: x.map(&:id), a: x.map(&:a), b: x.map(&:b)}
Upvotes: 1