back

Ruby Gotcha: Precedence of array insertion and or operators

This was a little bit surprising for me:

1
2
3
4
5
6
7
8


>> array = [1,2,3]
=> [1, 2, 3]
>> array << nil || 8
=> [1, 2, 3, nil]


The correct way to do this is:

1
2
3
4
5
6
7
8
9


>>  array = [1,2,3]
=> [1, 2, 3]
>> array << (nil || 8)
=> [1, 2, 3, 8]
>> 


December 30, 2009