将数组与数组数组合并

时间:2018-04-29 03:10:10

标签: arrays ruby

给定array1:

 [:lien_amount, :contact_number] 

给定Array2:

[[14646.75, nil], [69454.63, nil], [24989.53, nil], [74455.69, nil], [140448.19, nil], [12309.34, nil]]

我想:

{
  lien_amount: [14646.75, 69454.63, 24989.53, 74455.69,140448.19, 12309.34],
  contact_number: [nil, nil, nil, nil, nil, nil]
} 

所以我想将一个数组的键与数组数组中的值进行匹配。

我正在寻找单行代码解决方案。我尝试过:

array2.flat_map {|a| a.zip(array1)}

返回以下内容:

[[14646.75, :lien_amount], [nil, :contact_number], [69454.63, :lien_amount], [nil, :contact_number], ...

不是我想要的。但是想一想我想要的解决方案类型。

2 个答案:

答案 0 :(得分:4)

尝试以下方法:

array1.zip(array2.transpose).to_h

array2.transpose
# => [[14646.75, 69454.63, 24989.53, 74455.69, 140448.19, 12309.34], [nil, nil, nil, nil, nil, nil]]

array1.zip(array2.transpose)
# => [[:lien_amount, [14646.75, 69454.63, 24989.53, 74455.69, 140448.19, 12309.34]], [:contact_number, [nil, nil, nil, nil, nil, nil]]]

array1.zip(array2.transpose).to_h
# => {:lien_amount=>[14646.75, 69454.63, 24989.53, 74455.69, 140448.19, 12309.34], :contact_number=>[nil, nil, nil, nil, nil, nil]}

答案 1 :(得分:2)

arr1 = [:lien_amount, :contact_number] 
arr2 = [[14646.75, nil], [69454.63, nil], [24989.53, nil], [74455.69, nil],
        [140448.19, nil], [12309.34, nil]]

[arr1, arr2.transpose].transpose.to_h
  #=> {:lien_amount=>[14646.75, 69454.63, 24989.53, 74455.69, 140448.19, 12309.34],
  #    :contact_number=>[nil, nil, nil, nil, nil, nil]}

步骤如下。

a = arr2.transpose
  #=> [[14646.75, 69454.63, 24989.53, 74455.69, 140448.19, 12309.34],
  #    [nil, nil, nil, nil, nil, nil]]
b = [arr1, a]
  #=> [[:lien_amount, :contact_number],
  #    [[14646.75, 69454.63, 24989.53, 74455.69, 140448.19, 12309.34],
  #     [nil, nil, nil, nil, nil, nil]]]
c = b.transpose
  #=> [[:lien_amount, [14646.75, 69454.63, 24989.53, 74455.69, 140448.19, 12309.34]],
  #    [:contact_number, [nil, nil, nil, nil, nil, nil]]]
c.to_h
  #=> {:lien_amount=>[14646.75, 69454.63, 24989.53, 74455.69, 140448.19, 12309.34],
  #    :contact_number=>[nil, nil, nil, nil, nil, nil]}