简体   繁体   English

使用Ruby按两个条件对哈希数组进行分组

[英]Group an array of hashes by two conditions with Ruby

I have an array of hashes like so, I have removed some of the records for presentation purposes. 我有很多这样的哈希,为演示目的,我删除了一些记录。

[
  {
    "id"=>425343308605714432, 
    "text"=>"Hello", 
    "sender"=> {
      "id"=>1375480994, 
      "name"=>"Rocket"
    }, 
    "sender_id"=>1375480994, 
    "recipient"=> {
      "id"=>24766510,
      "name"=>"Max Rose-Collins"
    }, 
    "recipient_id"=>24766510, 
    "recipient_id_str"=>"24766510", 
    "recipient_screen_name"=>"maxrosecollins", 
    "created_at"=>"Mon Jan 20 19:05:21 +0000 2014" 
  },
  {
    "id"=>413305410666639361,  
    "text"=>"How are you", 
    "sender"=> {
      "id"=>24766510,  
      "name"=>"Max Rose-Collins"
    }, 
    "sender_id"=>24766510, 
    "sender_screen_name"=>"maxrosecollins", 
    "recipient"=> {
      "id"=>1375480994, 
      "name"=>"Rocket"
    }, 
    "recipient_id"=>1375480994, 
    "recipient_id_str"=>"1375480994", 
    "recipient_screen_name"=>"Rocket", 
    "created_at"=>"Wed Dec 18 13:51:03 +0000 2013"
  }
]

This array of hashes also contains other messages between other users. 此哈希数组还包含其他用户之间的其他消息。 I want to arrange this into conversations which contain the sent and received messages between two users. 我想将其安排在包含两个用户之间已发送和已接收消息的对话中。 I have tried using 我尝试使用

.group_by { |r| [r['recipient_id'], r['sender_id']] }

but this doesn't group them how I would have thought. 但这并不能将我的想法归类于他们。 It makes two groups one sent and the other received. 它分为两组,一组发送,另一组接收。

{
  [1375480994, 24766510]=>[removed for presentation], 
  [24766510, 1375480994]=>[removed for presentation],
  [24766510, 146385359]=>[removed for presentation],
  [146385359, 24766510]=>[removed for presentation],
}

How can I merge these two hashes into one so I have the whole of the conversation in one place, like a threaded conversation? 如何将这两个哈希合并为一个,以便将整个对话都放在一个地方,就像线程对话一样?

为了通过对话对它们进行分组,您可以将sort方法添加到group_by函数中:

.group_by{ |r| r.values_at('recipient_id', 'sender_id').sort }

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

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