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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+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. :-)
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.

5 Comments

Using parenthesis to force the order of precedence is better than changing from && to and. The code would be clearer with the additional parenthesis.
@theTinMan, I think that and has been built exactly for this type of situations. Using too many parenthesis can be messy.
Using too many parenthesis is an indicator of messy thinking and that the algorithm needs to be simplified or broken down.
@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 (github.com/styleguide/ruby).
@spickermann, thanks for the link. Apparently I was wrong. I've "fixed" the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.