Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1ruby-on-rails-2

On Rails, is there a shortcut to check for boolean defined variable and use its value or use a default if not defined?


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


Solution

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