簡體   English   中英

Rails分組並處理哈希數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM