Ruby - Difference between Array#<< and Array#push

Solution 1:

They are very similar, but not identical.

<< accepts a single argument, and pushes it onto the end of the array.

push, on the other hand, accepts one or more arguments, pushing them all onto the end.

The fact that << only accepts a single object is why you're seeing the error.

Solution 2:

Another important point to note here is that << is also an operator, and it has lower or higher precedence than other operators. This may lead to unexpected results.

For example, << has higher precedence than the ternary operator, illustrated below:

arr1, arr2 = [], []

arr1.push true ? 1 : 0
arr1
# => [1] 

arr2 << true ? 1 : 0
arr2
# => [true]