我有一個紅寶石哈希數組。這是結構:Rails group by和處理哈希數組
[ {
:question_id => 1
:topic_id => 2
}
{
:question_id => 1
:topic_id => 3
}
{
:question_id => 2
:topic_id => 1
}
...
]
我想這組由question_id
,並進一步串聯的topic_id
,這樣它看起來像:
[ {
:question_id => 1
:topic_id => 2,3
}
{
:question_id => 2
:topic_id => 1
}
...
]
group_by
讓我組,但是,topic_id
沒有串聯。
result.group_by{|h| h[:question_id]}.map do |question_id, hash|
{ question_id: question_id, topic_id: hash.map{|h| h[:topic_id].to_s + ","}}
end
什麼是乾淨的紅寶石的方式來做到這一點?
你能展示你試過的代碼嗎? – 2014-02-27 08:42:54
用代碼更新了問題。 –
@VarunJain,你不能簡單地把一個Ruby散列值變成逗號分隔列表__unless__該值是一個_array_。 – zeantsoi