通过合并两个哈希来形成新的哈希结构

时间:2014-08-08 07:17:45

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

我有两个相同格式的哈希。我的目标是通过从两个哈希中获取值来创建一个新的哈希,首先更改内部的键。我在下面的“我的目标”中解释了我希望作为输出的内容。我无法从这里前进,请帮忙。

我有什么

h1 = {
 "x"=> {
  "imp"=> {"a"=>1, "b"=>2},
  "ctr"=> {"a"=>3, "b"=>4}
  },
 "y"=> {
  "imp"=> {"c"=>1, "d"=>2},
  "ctr"=> {"c"=>3, "d"=>4}
  },
 "z"=> {
  "imp"=> {"e"=>10, "f"=>20, "g"=> 111},
  "ctr"=> {"e"=>30, "f"=>40, "g"=> 222}
   } 
} 

h2 = {
 "x"=> {
  "imp"=>{"a"=>11, "b"=>22},
  "ctr"=>{"a"=>33, "b"=>44}
 },
 "y"=> {
  "imp"=> {"c"=>11, "d"=>22},
  "ctr"=>{"c"=>33, "d"=>44}
 },
 "z"=> {
  "imp"=>{"e"=>11, "f"=>22, "g"=> 333},
  "ctr"=>{"e"=>55, "f"=>66, "g"=> 444}
 }
}

我的目标

{segment=>"x=a", "imp"=>1, "ctr"=>3, "imp_of_h2"=>11, "ctr_of_h2"=>33}, 
{segment=>"x=b", "imp"=>2, "ctr"=>4, "imp_of_h2"=>22, "ctr_of_h2"=>44},
{segment=>"y=c", "imp"=>1, "ctr"=>3, "imp_of_h2"=>11, "ctr_of_h2"=>33},
{segment=>"y=d", "imp"=>2, "ctr"=>4, "imp_of_h2"=>22, "ctr_of_h2"=>44},
{segment=>"z=e", "imp"=>10, "ctr"=>4, "imp_of_h2"=>22, "ctr_of_h2"=>55},
{segment=>"z=f", "imp"=>20, "ctr"=>40, "imp_of_h2"=>22, "ctr_of_h2"=>66},
{segment=>"z=g", "imp"=>111, "ctr"=>222, "imp_of_h2"=>333, "ctr_of_h2"=>444}

到目前为止我尝试了什么.. 但它仅适用于一个哈希值。我需要为两个哈希实现这一点。

data_final = []
h1.flat_map do |segment, attrs|
  segments = attrs.values.flat_map(&:keys).uniq
  # create a segment entry for each unique letter
  segments.map do |seg|
    row = {"segment" => "#{segment}=#{seg}"}
    row.merge! Hash[attrs.keys.map {|key| [key,attrs[key][seg]]}]
    data_final << row
  end      
end

1 个答案:

答案 0 :(得分:0)

从语用上讲,这是你想要的吗? (不要忘记为y_support方法安装Array#>> gem。)

require 'y_support/core_ext' # gem install y_support if necessary

labels = "imp", "ctr"
h2_suffix = "_of_h2"

result = [ [?x, ?a], [?x, ?b], [?y, ?c], [?y, ?d], [?z, ?e], [?z, ?f], [?z, ?g] ].map do
  |coordinate, letter|
  [ "segment", *labels, *labels.map { |lbl| lbl + h2_suffix } ] >>
    [ "#{coordinate}=#{letter}",
      *labels.map { |label| h1[coordinate][label][letter] },
      *labels.map { |label| h2[coordinate][label][letter] } ]
end