Rails分组并处理哈希数组

时间:2014-02-27 08:38:39

标签: ruby-on-rails ruby arrays data-structures hash

我有一系列红宝石哈希。这是结构:

[ {
  :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

干净的红宝石方法是什么?

2 个答案:

答案 0 :(得分:2)

hash.map{|h| h[:topic_id].to_s + ","}替换为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(',') } }

我希望你能得到你正在寻找的结果。

答案 1 :(得分: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]}]

这似乎符合您的要求?或者我误解了你的问题?