Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set a boolean default value in Ruby?

Tags:

ruby

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?

like image 339
evanrmurphy Avatar asked Nov 09 '12 04:11

evanrmurphy


People also ask

How do you set a boolean to default?

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.

What is the default value for a boolean?

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 .

Does Ruby have boolean?

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.”


2 Answers

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
like image 167
Andrew Marshall Avatar answered Sep 25 '22 09:09

Andrew Marshall


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.

like image 31
tadman Avatar answered Sep 22 '22 09:09

tadman