Search code examples
rubyvariablesconditional-statementslocalwebistrano

Assigning a variable based on existence of other variables in ruby 1.9


I got the job to fix a webistrano installation and now I am stuck in the situation where I have a receipt wherein the following assignment broke after the update from ruby 1.8 to ruby 1.9.3

if defined? var_one != nil
  var_to_be_used = var_one
else
  $logger.info(var_one)
  var_to_be_used = var_two
end

I have made sure (by adding the above log-entries) that var_one and var_two hold the expected values. For example when I expect var_one to hold the value I got following log:

** value in var_one
*** undefined local variable or method `var_two' for #<Capistrano::Configuration::Namespaces::Namespace:0x000000032a6040>

The first case is never reached. The script always goes to the else case - even when var_one holds a string.

How can I fix it?


Solution

  • I solved it with

    var_to_be_used ||= var_one rescue var_to_be_used ||= var_two rescue nil
    

    accessing via var_one.nil? caused undefined local variable or method 'var_one' again.