开发者

Ruby: Why does 'and not' work when '&& !(expr)' does not?

开发者 https://www.devze.com 2022-12-20 02:56 出处:网络
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:

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?


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.


‘not’ is a control operator, ! is a logical operator. The difference is that ‘not’ has lower priority when evaluating the command. Use ! when you do logical expressions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号