How can you construct an array in Ruby which only uses a variable if it exists, and otherwise uses
a = 1
c = 3
arr = [a, b || nil, c]
(b || nil)
b ? b : nil
b.nil? ? nil : b
Given that your
b is actually a model attribute which may or may not be supported by the current
b is not a variable at all,
b is a method call and you're not interested in whether or not the "variable" exists, you're interested in whether or not
self responds to
b. Hence you want to use
arr = [a, respond_to?(:b) ? b : nil, c]
arr = [a, respond_to?(:b, true) ? b : nil, c]
if you want to allow
b to be a non-public method.
defined?(b) should also work in this case (unless
b's accessor method is automatically created via
method_missing) but it will be rather puzzling to anyone looking at your code. Using
respond_to? to see if an object has a method/attribute would be more idiomatic.
respond_to? when faced with
method_missing of course assumes that both
respond_to? have been overridden but that should be a relatively safe assumption.