How can you construct an array in Ruby which only uses a variable if it exists, and otherwise uses nil in its place. With the conditional logic inside the array constructor.
Simplified Example:
a = 1
c = 3
arr = [a, b || nil, c]
I've tried a number of different way but they are not working so I feel like I'm missing something fundamental here.
(b || nil)b ? b : nilb.nil? ? nil : b
Is this possible?
Context:
This array constructor is used inside a loop used by multiple different models. Some models have the b attribute and some do not, making it difficult extrapolate the logic outside.
bnot exist? That's really an unusual thing to see in Ruby code.battribute and some do not". The first says thatbis a variable, the second says thatbis a method call, which is it?@instance.attribute_b. The method with this logic iterates over query results for several different models (separately); some of the models do not have anattribute_b.