Daniel Viglione
Daniel Viglione

Reputation: 9457

ruby operator precedence issue with shift operator

I had a general knowledge of this. It is the operator precedence chart. The shift operator has higher precedence than the logical operators (&& ||). I had a situation like this, where arr was an array and party was nil:

arr << party && party[3]

Now initially when I did this I thought if party was nil than party[] would never be called. Of course, since << has higher precedence it tries this first:

arr << party

But what happens next? Does ruby then do this:

arr << party[3]

Note that I used the highest operator () to resolve the issue:

arr << (party && party[3])

Upvotes: 1

Views: 58

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230471

<< operator on arrays returns the array. So if party is nil, nil gets pushed to arr and then party[3] is evaluated as part of boolean expression (because left part of the expression is truthy and didn't short-circuit). Since party is nil, an error will be raised here.

Actually, << operator gets resolved to << method of Array class. Which is very much like push. But it, being an operator, has different precedence, yes. If you were to use a method, it'd work more like you expect.

arr.push party && party[3] # => [nil]
arr.<< party && party[3] # => [nil]

Me, I put parentheses everywhere where there's even a shadow of doubt.

arr.push(party && party[3])

Also, not sure about intentions, but there might be a little bug in your code. The line above will always push something to arr. One of false, nil and party[3]. If you want to not do anything with a falsy value, then it's better to do something like this

arr << party[3] if party

Upvotes: 3

Related Questions