迭代两个哈希值,求和值并使用新键创建第三个哈希值

时间:2017-09-13 12:07:34

标签: ruby hash

我有两个哈希数组,我尝试创建第三个哈希数组,将dates中的每个值添加到每个times值。

dates=[{a:­1},{a:2},{­a:3}]
times=[{f:7,t:8}­,{f:9,t­:10},{f:11,t:12­}]

我知道两个单一的哈希

dates={a:1}
times={f:7,t:8}

我能做到

a=[]
h={}
h[:from]=d­ates[:a]+times[:f]
h[:to]=dates[:a]+times­[:t]
a<<h

=> [{:from=>8, :to=>9}]

我如何迭代以使上面的哈希数组发生这种情况,好吗?

我想要的结果是[{:from=>8,:to=>9},{:from=>10,:to=>11}, {:from=>12,:to=>13},{:from=>9,:to=>10},{:from=>11,:to=>12},{:from=>13,:to=>14},{:from=>10,:to=>11},{:from=>12,:to=>13},{:from=>14,:to=>15}]

2 个答案:

答案 0 :(得分:3)

由于您所需的结果为[{:from=>8,:to=>9},{:from=>10,:to=>11}..],我认为Cartesian product正是您所寻找的。

幸运的是,Ruby中有Array#product,这就是为什么解决方案就像这样简单:

dates=[{a:1},{a:2},{a:3}]
times=[{f:7,t:8},{f:9,t:10},{f:11,t:12}]

result = dates.product(times).map do |date, time|
  {from: date[:a] + time[:f], to: date[:a] + time[:t]}
end

puts result

答案 1 :(得分:1)

dates.product(times).map do |d,t|
  n = d[:a]
  t.transform_values { |v| v + n }
end
  #=> [{:f=>8, :t=> 9}, {:f=>10, :t=>11}, {:f=>12, :t=>13},
  #    {:f=>9, :t=>10}, {:f=>11, :t=>12}, {:f=>13, :t=>14},
  #    {:f=>10, :t=>11}, {:f=>12, :t=>13}, {:f=>14, :t=>15}]

第一步是

dates.product(times)
  #=> [[{:a=>1}, {:f=>7, :t=>8}], [{:a=>1}, {:f=>9, :t=>10}], [{:a=>1}, {:f=>11, :t=>12}],
  #    [{:a=>2}, {:f=>7, :t=>8}], [{:a=>2}, {:f=>9, :t=>10}], [{:a=>2}, {:f=>11, :t=>12}],
  #    [{:a=>3}, {:f=>7, :t=>8}], [{:a=>3}, {:f=>9, :t=>10}], [{:a=>3}, {:f=>11, :t=>12}]]

Array#productHash#transform_values,后者已在v2.4中首次亮相。