Best way to replace nils from an array with elements of another array

I have two arrays:

a = [nil, 1, nil]
b = [4, 5, 6]

      

And I want to replace nil elements from the first array with related elements from the second array:

[4, 1, 6]

      

What's the best way to do this?

+3


source to share


5 answers


You can also use the zip

operator for this ||

:



result = a.zip(b).map{ |x,y| x || y } 

      

+6


source


If you want to replace exactly nil

but not false

elements:



a.map.with_index { |e, i| e.nil? ? b[i] : e }
# => [4, 1, 6]

      

+5


source


you can use

a.zip(b).map(&:compact).map(&:first) #=> [4, 1, 6]

      

Steps:

a.zip(b)
#=> [[nil, 4], [1, 5], [nil, 6]]
a.zip(b).map(&:compact)
#=> [[4], [1, 5], [6]]
a.zip(b).map(&:compact).map(&:first)
#=> [4, 1, 6]

      

Because of Array#compact

this, this approach nil

only removes items from archived pairs, i.e. items are false

not removed.

+5


source


Another way is to use a block when creating this new array like so:

a = [nil, 1, nil]
b = [4, 5, 6]
Array.new(a.size) { |i| a[i].nil? ? b[i] : a[i] }
#=> [4, 1, 6]

      

+3


source


Another option:

a.zip(b).map{|a, b| [*a, *b].first}
# => [4, 1, 6]

      

This differs nil

from false

, as expected. But note that you cannot use this with split elements, for to_a

example hashes.

0


source







All Articles