2

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

p.matsinopoulos
  • 7,655
  • 6
  • 44
  • 92

2 Answers2

2

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.

Richard Brown
  • 11,346
  • 4
  • 32
  • 43
  • Thanks a lot. Can you please explain how this one works? It is very strange to me that this statement does not throw "undefined local variable or method `aVar' for main:Object". – p.matsinopoulos Mar 30 '13 at 07:57
  • Sorry, did this late last night. I amended the answer with an explanation. – Richard Brown Mar 30 '13 at 16:19
  • My surprise here is that if I just type "aVar.nil?" on an irb console, it throws "NameError: undefined local variable or method ...", but if I type in the "aVar ||= aVar.nil?" it does not throw any. Do you have an explanation for that? – p.matsinopoulos Mar 30 '13 at 23:34
  • 1
    The ||= operator will always return a valid value, regardless if the variable exists, therefore it will never throw an error. See http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators#Operators – Richard Brown Mar 30 '13 at 23:46
-2

You can try:

if var.present?  
 var  
else  
 true  
end
oz123
  • 27,559
  • 27
  • 125
  • 187
nilay
  • 365
  • 1
  • 10