我有一个像这样的哈希数组,我已经删除了一些记录用于演示目的。
[
{
"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"
}
]
此哈希数组还包含其他用户之间的其他消息。 我想将其安排到包含两个用户之间发送和接收消息的会话中。 我尝试过使用
.group_by { |r| [r['recipient_id'], r['sender_id']] }
但这并没有将他们的想法分组。它使两个组一个发送,另一个组接收。
{
[1375480994, 24766510]=>[removed for presentation],
[24766510, 1375480994]=>[removed for presentation],
[24766510, 146385359]=>[removed for presentation],
[146385359, 24766510]=>[removed for presentation],
}
如何将这两个哈希合并为一个,这样我就可以在一个地方进行整个对话,比如一个线索对话?
答案 0 :(得分:3)
要按对话对其进行分组,您可以将sort
方法添加到group_by
函数中:
.group_by{ |r| r.values_at('recipient_id', 'sender_id').sort }