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?
You can also use the zip
operator for this ||
:
result = a.zip(b).map{ |x,y| x || y }
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]
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.
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]
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.