1

Given array1:

 [:lien_amount, :contact_number] 

Given Array2:

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

I want:

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

So I want to match the keys of one array with the values in the array of arrays.

I am looking for a one-line-of-code solution. What I have tried:

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

This returns the following:

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

Not what I was looking for. But gives an idea of the type of solution I want.

1

2 Answers 2

4

Try to the following:

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]}
Sign up to request clarification or add additional context in comments.

1 Comment

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]}

The steps are as follows.

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]}

1 Comment

Awesome way of using transpose!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.