Hernan Acosta
Hernan Acosta

Reputation: 397

Ruby showel operator vs (?:) conditional

I have the following code:

@ids = []
x = 'a'
@ids << x == 'a' ? [1,2] : [3,4]
@ids

I expect that in next line the @ids value should be @ids = [1,2], but I obtain @ids = ['a']

Why ?

Upvotes: 3

Views: 60

Answers (1)

wteuber
wteuber

Reputation: 1238

Operations are executed in the order of their precedence. The operations in your relevant line of code are executed in that order:

  1. <<
  2. ==
  3. ?, :

See the full list at Ruby's operation precedence.

Here, parenthesis indicate what actually happens in your example:

(((@ids << x) == 'a') ? [1,2] : [3,4])
^^^----1----^       ^                ^
||---------2--------|                |
|------------------3-----------------|

To get the result you expected, write

@ids << (x == 'a' ? [1,2] : [3,4])

or

@ids.push(x == 'a' ? [1,2] : [3,4])

I hope you find this helpful.

Upvotes: 6

Related Questions