1

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]) 
1
  • 1
    As a general practice it's good to use parenthesis to force precedence whenever you think an interpreter or compiler will not understand your expression. A language (like Ruby) might make them optional, but not using them can cause weird/unexpected behaviors. Commented Mar 24, 2017 at 22:03

1 Answer 1

3

<< 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 
Sign up to request clarification or add additional context in comments.

2 Comments

Good answer. Personally, I think the shovel operator is more intuitive, and using it here would be fine using your alternative syntax: arr << party[3] if party.
"I put parentheses everywhere where there's even a shadow of doubt." Ditto. They don't cost anything and can save a lot of head pounding.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.