Ruby-on-rails – Rails – How to check if a variable exists and also if it has a certain value in one statement

ruby, ruby-on-rails, undefined

Currently if it doesn't exists I get a the undefined local variable or method error.

How can I check the value of the variable and also account for it not existing at all.

I thought && was the deal but:

if defined? aaa && aaa == '123' then puts aaa endNameError: undefined local variable or method `aaa' for main:Object

Best Solution

In this case, you need the parenthetical like defined?(aaa) otherwise it is evaluating the entire expression aaa && aaa == '123' as if it were defined?(aaa && aaa == '123'). So your code is really doing this:

if defined?(aaa && aaa == '123') # returns "expression" string, and thus true  puts aaa # the error comes from this part, since aaa is not defined.end