3

Why do I get the following error:

irb >> x == "AN" && arr.include? ("bar")
 SyntaxError: (irb):80: syntax error, unexpected tLPAREN_ARG, expecting $end
x == "AN" && arr.include? ("bar")
                           ^

But this works fine:

x == "AN" && (arr.include? ("bar"))

It looks to be doing this: ( x == "AN" && arr.include? ) && ("bar"). What the ambiguity here?

HeretoLearn
  • 7,124
  • 6
  • 24
  • 22

2 Answers2

3

You shouldn't be spacing out your arguments, it leads to confusing interpretations:

x == "AN" && arr.include?("bar")

The ambiguity is in trying to determine if ("bar") is an argument or something else.

There are occasions where you can get away with the space, but it's generally a habit you don't want to get into.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • 3
    +1 for "it's generally a habit you don't want to get into." While I occasionally take advantage of Ruby's ability to ignore parenthesis for parameters, I find it a lot easier to read the code with them, plus I know the interpreter will honor MY use of parenthesis over its own built-in heuristics. I'm the programmer and it's the interpreter and I don't want it to think different. :-) – the Tin Man Sep 13 '13 at 17:00
2

&& has a very strong precedence therefore irb is parsing it as:

x == ("AN" && arr.include?) ("bar")
# Syntax error

leading to the error (especially because of the space between include? and ().

You may want to use parenthesis to ensure the correct order for the evaluation:

(x == "AN") && arr.include?("bar")
# true / false

In this case you can also use and:

x == "AN" and arr.include? ("bar")
# false / true 

which have a lower precedence.

Community
  • 1
  • 1
Shoe
  • 74,840
  • 36
  • 166
  • 272
  • 1
    Using parenthesis to force the order of precedence is better than changing from `&&` to `and`. The code would be clearer with the additional parenthesis. – the Tin Man Sep 13 '13 at 16:57
  • @theTinMan, I think that `and` has been built exactly for this type of situations. Using too many parenthesis can be messy. – Shoe Sep 13 '13 at 16:58
  • Using too many parenthesis is an indicator of messy thinking and that the algorithm needs to be simplified or broken down. – the Tin Man Sep 13 '13 at 17:11
  • @Jefffrey , I do not think that `and` was build for such situations. I think it is best practice to use `&&` for boolean expression and `and` for control flow. Some people think you should never use `and` and `or` (https://github.com/styleguide/ruby). – spickermann Sep 13 '13 at 17:50
  • @spickermann, thanks for the link. Apparently I was wrong. I've "fixed" the answer. – Shoe Sep 13 '13 at 21:34