Jeremy Thomas
Jeremy Thomas

Reputation: 6674

Rails 4: Combine array of hashes

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

Answers (1)

zwippie
zwippie

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

Related Questions