3

Disjunction and conjunction in words (or, and) in argument position require additional parentheses, as opposed to ||, &&.

def foo _; end

foo(1 || 2) # => Good
foo(1 or 2) # => Syntax error
foo((1 or 2)) # => Good

foo(1 && 2) # => Good
foo(1 and 2) # => Syntax error
foo((1 and 2)) # => Good

Why do they need additional parentheses?

sawa
  • 165,429
  • 45
  • 277
  • 381

1 Answers1

3

I think it's because logical composition operators and and or have lower precedence than a method's argument list, so the parser fails when another list argument or enclosing parenthesis is not found.

On the other hand logical operators && and || have higher precedence so their arguments are evaluated sooner and result of the expression then passed to method as an argument.

Standalone parenthesis change associativity, so foo (1 or 2) does work and 1 is passed as a result to foo method.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
David Unric
  • 7,421
  • 1
  • 37
  • 65
  • @sawa Yep, parens enclosing method arguments is a quite different case then parens enforcing associativity of evaluation. For the former, space after method name is disallowed. – David Unric Aug 05 '14 at 23:07
  • The [Ruby style guide does recommend just saying no to `and` and `or`](https://github.com/bbatsov/ruby-style-guide#no-and-or-or). Be careful with the space trick. If your method then takes 2 arguments the first being the `(1 or 2)` You would need to do `foo (1 or 2),3` `foo (1 or 2,3)` is similarly a syntax error. Also of interest, with a single argument method, you may be inclined to delete the parenthesis yielding different results: `foo 1 or 2` === `foo(1) or 2` ==> `2` but `foo 1 || 2` === `foo(1 || 2)` ==> `nil` – Charlie Aug 05 '14 at 23:18
  • @Charlie Good points, just a little nitpick to example with multiple method arguments. The expression `foo (1 or 2,3)` is a bit different to previous examples and unrelated to `foo` method. `(1 or 2,3)` alone is just an invalid expression, ie. `(_, _)` is not a valid constructor in Ruby. – David Unric Aug 05 '14 at 23:35