[英]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? 如果我有一个ActiveRecord对象数组,并且想按属性组合它们,该怎么办?
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)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.