On Ruby on Rails 3, I am trying to use the value of a boolean variable, if defined, otherwise use default value true. How should I write something like this?
if var.defined?
var
else
true
end
Thanks in advance
You can do:
aVar ||= aVar.nil?
Which will assign the value true if the variable doesn't already have a value.
The ||=
operator assigns the right value to the left variable if the left variable doesn't have a value. It's great for assigning default values to variables. The aVar.nil?
returns true if aVar
doesn't exist or has a nil
value. All together it achieves what you were looking to do.