Reputation: 397
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
Reputation: 1238
Operations are executed in the order of their precedence. The operations in your relevant line of code are executed in that order:
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