-2

Lets say I have the following line of code: return nil unless app && ip || device

Without parenthesis, how will Ruby interpret the precedence? (app && ip) || device? or app && (ip || device)?

Or some other way?

Thanks!

Ricky Mason
  • 1,838
  • 6
  • 31
  • 60
  • @nietonfir did you read both questions? They are completely different. – Marek Lipka Mar 19 '14 at 13:48
  • http://en.wikipedia.org/wiki/Logical_connective#Order_of_precedence – Marek Lipka Mar 19 '14 at 13:48
  • @MarekLipka I fail to see how that Wikipedia page is relevant to the question. In fact, it is quite misleading, since in Ruby, there's the special case of `and` which has lower precedence than `&&` and `||`. – Frank Schmitt Mar 19 '14 at 13:51
  • @FrankSchmitt this question is about precedence between `&&` and `||`, not between `&&` and `and`. And in this scope Ruby meet expectations from mathematical logical operators - `&&` has precedence over `||` (and, accordingly, `and` has precedence over `or`) . – Marek Lipka Mar 19 '14 at 13:53
  • @MarekLipka That's true, but I still consider it misleading in this context, since Ruby has the specialty of lower-precedence variants of these operators. But YMMV, of course. – Frank Schmitt Mar 19 '14 at 13:59

1 Answers1

4

It's simple - since && has higher precedence than ||, it will be interpreted as

  (app && ip) || device

I'd recommend to always add the parentheses for readability purposes, though.

See e.g. Rosettacode page on operator precedence for Ruby

Frank Schmitt
  • 30,195
  • 12
  • 73
  • 107