2015-03-31 24 views
-1

下面是來自PGResult集合的散列數組。如何更好地處理散列數組

result = [ 
    {"type" => 1 , "original" => "true", "count" => "10"}, 
    {"type" => 1 , "original" => "false", "count" => "20"}, 
    {"type" => 2 , "original" => "false", "count" => "30"}, 
    {"type" => 2 , "original" => "true", "count" => "40"}, 
    {"type" => 3 , "original" => "true", "count" => "50"}, 
    {"type" => 3 , "original" => "false", "count" => "60"} 
] 

我想處理上面的哈希數組爲下面的格式。 total_count =原始計數(「真」) - 每種類型的原始計數(「假」)!

[ 
    {"type" => 1, "total_count" => "-10"}, 
    {"type" => 2, "total_count" => "10"}, 
    {"type" => 3, "total_count" => "-10"} 
] 

任何提示處理上述數組?

+0

你的結果似乎不符合你的描述不應該輸入1在這種情況下是-10? (10 - 20) – engineersmnky 2015-03-31 13:51:05

回答

1
result.group_by {|h| h['type']}.values.map do |h1, h2| 
    new_hash = {"type" => h1["type"]} 
    new_hash["total_count"] = h1["original"] == "false" ? h1["count"].to_i - h2["count"].to_i : h2["count"].to_i - h1["count"].to_i 
    new_hash 
end 
# => [{"type"=>1, "total_count"=>10}, {"type"=>2, "total_count"=>-10}, {"type"=>3, "total_count"=>10}] 
2

如何像:

result = [ 
    {"type" => 1 , "original" => "true", "count" => "10"}, 
    {"type" => 1 , "original" => "false", "count" => "20"}, 
    {"type" => 2 , "original" => "false", "count" => "30"}, 
    {"type" => 2 , "original" => "true", "count" => "40"}, 
    {"type" => 3 , "original" => "true", "count" => "50"}, 
    {"type" => 3 , "original" => "false", "count" => "60"} 
] 

# will be used to extract "proper" value - positive or negative 
to_value = -> (group) do 
    value = group["count"].to_i 
    group["original"] == "false" ? -value : value 
end 

groups = result.group_by { |h| h["type"] } 

counts = groups.map do |num, group| 
    { "type" => num, 
    "total_count" => group.map(&to_value).inject(:+) } 
end 

p counts 
# => [{"type"=>1, "total_count"=>-10}, {"type"=>2, "total_count"=>10}, {"type"=>3, "total_count"=>-10}] 

希望幫助!

感謝您對lambda的建議!@engineersmnky!

+0

我喜歡在這裏使用拉姆達,但我倒了'group [「original」] ==「false」? -value:value'比早期的return語句更簡潔一點,也更簡單。 – engineersmnky 2015-03-31 13:53:13

+0

@engineersmnky - 嘿!這很聰明!感謝您指出了這一點! – 2015-03-31 14:00:53

+1

既然你也接受了建議,'each_with_object([])'和'map'是一樣的,只需要'ret'對象,'inject(0,:+)'可以是'inject(:+)''或'reduce(:+)' – engineersmnky 2015-03-31 14:12:48