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]}
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)}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.