1

I was geting the following error in my code:

a = 1
array = [1, 2]
array.include? a
=> true

a == 1 || array.include? a
=> syntax error, unexpected tIDENTIFIER, expecting end-of-input

I was thinking that you cannot have a space in an OR statement, or end with a variable, however the following code block works fine:

array.include? a || 1 == a
=> true

Then I managed to figure out how to get it to work:

a == 1 || array.include?(a)
=> true

I am so confused, can anyone explain?

Dennis
  • 100
  • 1
  • 10

1 Answers1

2

It's a Ruby precedence issue. When you run a == 1 || array.include? a ...operations are executed in an order that is not necessarily intuitive (without parens). To verify, you can try

a == 1 or array.include? a

which should return true (or has a lower precedence than || in Ruby).

You can checkout this question for further clarification.

Mark Merritt
  • 2,625
  • 2
  • 12
  • 16
  • Ok I think I get it, so because || has very high precedence, ruby sees the || and is trying to evaluate whether "array.include? a" is true or false, but it is doing this before it has gotten around to actually calculating the value of "array.include? a", so it throws an error. Is this right? – Dennis Aug 01 '18 at 01:36