2014-02-27 92 views
-1

我有一個紅寶石哈希數組。這是結構: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 

什麼是乾淨的紅寶石的方式來做到這一點?

+0

你能展示你試過的代碼嗎? – 2014-02-27 08:42:54

+0

用代碼更新了問題。 –

+1

@VarunJain,你不能簡單地把一個Ruby散列值變成逗號分隔列表__unless__該值是一個_array_。 – zeantsoi

回答

0

隨着.to_s + ","位的刪除,你的代碼已經看起來正確嗎?

result = [{:question_id => 1, :topic_id => 2}, {:question_id => 1, :topic_id => 3}, {:question_id => 2, :topic_id => 1}] 

result.group_by{|h| h[:question_id]}.map { |question_id, hash| { question_id: question_id, topic_id: hash.map{|h| h[:topic_id]}} } 
=> [{:question_id=>1, :topic_id=>[2, 3]}, {:question_id=>2, :topic_id=>[1]}] 

這似乎符合你在找什麼?或者我誤解了你的問題?

2

hash.map{|h| h[:topic_id]}.join(',')

result = [ { :question_id => 1, :topic_id => 2 },{:question_id => 1, :topic_id => 3 },{ :question_id => 2, :topic_id => 11 }] 
result.group_by{|h| h[:question_id]}.map{ |q_id, hashes_array| {:question_id => q_id, :topic_id => hashes_array.map{|hash| hash[:topic_id]}.join(',') } } 

更換hash.map{|h| h[:topic_id].to_s + ","}我希望你會得到結果,而您正在尋找。