0

Will every && run before if on the same line in Ruby?

For example:

@building.approved = params[:approved] if xyz && abc && mno...

Can an unlimited number of && be used on the right side of an if without using parentheses?

I'm inclined to use parentheses but I'd like to understand the default behaviour.

tim_xyz
  • 11,573
  • 17
  • 52
  • 97
  • 2
    Possible duplicate of [Ruby operator precedence table](http://stackoverflow.com/questions/21060234/ruby-operator-precedence-table) – Makoto Sep 29 '16 at 17:46
  • I don't think this is an exact duplicate of the nominated exemplar: Knowing operator precedence won't help the OP, since `if` is not an operator. – Wayne Conrad Sep 29 '16 at 17:56

1 Answers1

2

Everything after the if must be part of the condition by virtue of the syntax. The only way to get around this is to be really specific:

(@building.approved = params[:approved] if xyz) && abc && ...

Which is obviously not what you're intending here.

Operator binding strength isn't an issue here since if is a syntax element not an operator, so it has the absolute lowest priority.

The only conditions that will be evaluated are the ones that produce a logically false value, or come after one that was logically true as the first one to return logically false will halt the chain.

That is:

if a && b && c

Will stop at a if that is a logically-false value. b and c will not be evaluated. There's no intrinsic limit on chaining though.

tadman
  • 208,517
  • 23
  • 234
  • 262