iamse7en iamse7en - 21 days ago 6
Ruby Question

Manipulating multiple arrays with multiple criteria

a = [nil, nil, 40, 30]
b = [nil, 20, nil, 50]


I want to: Compare a & b. If both positions are nil, set them equal to 0. If one is nil, set it equal to the non-nil #. If both are non-nil, set leave them as is.

In other words, I'm looking for this result:

a = [0, 20, 40, 30]
b = [0, 20, 40, 50]


Thank you!

Edit: Clarify, if both are non-nil, then return them as is. Bad example to leave this case out, so I edited it above.

Answer

nil || x will yields x (because nil is falsy value is ruby)

nil || 2   # fallback to second value if the first value is `nil`
# => 2
nil || nil || 0  # fallback to 0 if both values are 0
# => 0
2 || nil  # Use the first value
# => 2

Using such characteristic, you can do something like:

a = [nil, nil, 40, nil, -1]
b = [nil, 20, nil, nil, 2]

a, b = a.zip(b).map { |x, y| [x||y||0, y||x||0] }.transpose
# a => [0, 20, 40, 0, -1]
# b => [0, 20, 40, 0, 2]