如何以更好的方式处理哈希数组

时间:2015-03-31 09:38:31

标签: ruby-on-rails ruby arrays ruby-on-rails-3 hash

下面是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 =原始计数(" true") - 每种类型的原始计数(" false")!

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

处理上述数组的任何提示?

2 个答案:

答案 0 :(得分: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的建议!

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