0

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

[{"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"} }
4

2 回答 2

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"}}
于 2012-06-20T20:07:03.160 回答
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

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

于 2012-06-20T19:55:40.787 回答