views:

62

answers:

1

I have an if statement in my Rails app. I need to do a basic "if true and !false" sort of check. The expression is defined as:

ActiveRecord::Base.connection.tables.include? 'settings' && !Settings.setting_is_set?('defaults_set')

If I put that as my expression to an if, the if will not trigger. If I run that expression in the console, I get false.

Now, if I modify the expression to read:

ActiveRecord::Base.connection.tables.include? 'settings' and not Settings.setting_is_set?('defaults_set')

It returns true as it should, and the executes it's block.

So the question is: Why is 'expression && !expression' not behaving like 'expression and not expression'. It's my understanding && and ! should correspond to and and not almost directly.

What am I missing here?

+3  A: 

Its because when you use && Ruby is interpreting the entire end of the string as a single argument being passed to include. Put parenthesis around the 'settings' and the first statement will work fine:

ActiveRecord::Base.connection.tables.include? 'settings' && !Settings.setting_is_set?('defaults_set')
# => false

ActiveRecord::Base.connection.tables.include?('settings') && !Settings.setting_is_set?('defaults_set')
# => true

Somehow, when you use and not it knows that the second part is not part of what is being passed to include and your call succeeds.

Doug Neiner
Andrew Grimm
This did the trick. Thank you.
Matt
I never use and/or, only and/or don't.
Shadowfirebird