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?
Use the create() or update() methods to specify the value of the new property as its default value, that is, false for boolean or 0 for integer.
The default value of Boolean is False . Boolean values are not stored as numbers, and the stored values are not intended to be equivalent to numbers. You should never write code that relies on equivalent numeric values for True and False .
Every object in Ruby has a boolean value, meaning it is considered either true or false in a boolean context. Those considered true in this context are “truthy” and those considered false are “falsey.” In Ruby, only false and nil are “falsey,” everything else is “truthy.”
You must have defined?
first, else the parser reaches x =
and then defines x
(which makes it nil
) before running the unless
:
defined?(x) or x = true
x #=> true
x = false
defined?(x) or x = true
x #=> false
Doing a if
/unless
block (instead of post-if
/unless
one-liner) also works:
unless defined?(x)
x = true
end
x #=> true
x = false
unless defined?(x)
x = true
end
x #=> false
There are only two non-true values in Ruby: false
and nil
. All you need to do is differentiate between those. Until the new //=
operator that does this automatically comes around, you're stuck with this:
if (x.nil?)
x = true
end
Hopefully this can be abbreviated in future versions of ruby. 99% of the time you don't really care about the difference between the two non-true values, but that 1% of the time you do it becomes annoying to have to be so unusually verbose.
Remember that the defined?
operator will always return "local-variable"
for that condition because the variable x
is "defined" as a local variable. Contrast with defined?(nope)
and you'll get nil
because that variable does not exist. Ruby is concerned with the variable or constant in question, not if that variable or constant has been defined with a value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With