在ruby中分组并格式化散列值数组

时间:2012-06-20 19:29:40

标签: ruby arrays grouping

嘿,我有一个哈希值数组,如下所示。

[{"group" => "1", "message" => "hey", "weight" => 1}, {"group" => "1", "message" 
 => "hey1", "weight" => 2}, {"group" => "2", "message" => "hey3", "weight" => 4}]

我想将group_by分组并格式化,以便获得以下内容:

[{"group" => 1, "messages" => {"hey","hey1"}, "weights" => {1,2}}, {"group" => 2,
  "messages" => {"hey3"}, "weights" => {4}}]

有没有一种很好的红宝石方法来实现这个目标?

修改:现在我有:

[
  {"group" => "1", "message" => {"hey" => "1"}},
  {"group" => "1", "message" => {"hey1" => "2"}}
]

我想要

{"group" => "1", "messages" => {"hey1" => "1", "hey2" => "2"} }

2 个答案:

答案 0 :(得分:2)

根据您修改后的问题:

groups = [
  {"group" => "1", "message" => {"hey" => "1"}},
  {"group" => "1", "message" => {"hey1" => "2"}}
]

merged = groups.inject do |h1,h2|
  h1.merge(h2) do |k,v1,v2|
    if v1==v2
      v1
    elsif v1.is_a?(Hash) && v2.is_a?(Hash)
      v1.merge(v2)
    else
      [*v1,*v2]
    end
  end
end

p merged
#=> {"group"=>"1", "message"=>{"hey"=>"1", "hey1"=>"2"}}

答案 1 :(得分:1)

我认为你想要的输出是:

[{"messages"=>["hey", "hey1"], "weights"=>[1, 2], "group"=>"1"}, {"messages"=>["hey3"], "weights"=>[4], "group"=>"2"}]

如果是这种情况,此代码可以满足您的需求:

h.group_by { |item| item["group"] }.values.map do |item|
    item.inject({"messages" => [], "weights" => []}) do |result, subitem|
        result["group"] = subitem["group"]
        result["messages"] << subitem["message"]
        result["weights"] << subitem["weight"]
        result
    end
end

你应该能够更多地了解你的具体问题,但它应该是一个很好的起点。