[英]Rails group by and process array of hashes
我有一系列的紅寶石哈希值。 結構如下:
[ {
:question_id => 1
:topic_id => 2
}
{
:question_id => 1
:topic_id => 3
}
{
:question_id => 2
:topic_id => 1
}
...
]
我想按question_id
進行分組,然后進一步將topic_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
什么是干凈的紅寶石方法?
替換hash.map{|h| h[:topic_id].to_s + ","}
hash.map{|h| h[:topic_id].to_s + ","}
和hash.map{|h| h[:topic_id]}.join(',')
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(',') } }
希望您能得到想要的結果。
僅刪除.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]}]
這似乎符合您的需求? 還是我誤會了你的問題?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.