For other types of variables, I use ||=
, but this doesn't work for booleans (x ||= true
assigns x to true even if x was previously assigned to false).
I'd thought that this would work:
x = true unless defined?(x)
But it doesn't: it assigns x to nil for some reason. (An explanation here would be appreciated.)
I do know one method that works:
unless defined?(x)
x = true
end
But it's rather verbose. Is there a more concise way to assign default values to boolean variables in Ruby?