简体   繁体   English

如何在哈希数组中分组

[英]how to group by in a array of hashes

I have a array of hashes 我有很多哈希

and I need to be able to group them by users. 并且我需要能够按用户对它们进行分组。

      order = Order.find(options[:order_id])
      shipments = order.shipments.select {|shipment| shipment["roundtrip_shipment"] == nil }.collect {|o| {
        id: o.id,
        user_id: o.user_id,
        ...
      } }

I am having some problems in making a group by in the array. 我在数组中进行分组时遇到了一些问题。

I have tried to do shipments = order.shipments.group_by { |shipment| shipment[:user_id] }.count 我已经尝试过进行shipments = order.shipments.group_by { |shipment| shipment[:user_id] }.count shipments = order.shipments.group_by { |shipment| shipment[:user_id] }.count

but this always returns 1 when I know that have 2 users here Thanks for all the help 但是当我知道这里有2个用户时,它总是返回1。感谢所有帮助

You can simply do as follow: 您可以简单地执行以下操作:

order = Order.find(options[:order_id])
shipments = order.shipments.where.not(roundtrip_shipment: nil).group_by(&:user_id).collect {|x,y| {x => y.map(&:id)} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM