starred.sort_by { |a| [a ? 1 : 0, a] }
When it has to compare two elements, it compares an arrays. When Ruby compares arrays (calls ===
method), it compares 1st element, and goes to the 2nd elements only if the 1st are equal. ? 1 : 0
garantees, that we'll have Fixnum as 1st element, so it should be no error.
If you do ? 0 : 1
, nil
will appear at the end of array instead of begining.
Here is an example:
irb> [2, 5, 1, nil, 7, 3, nil, nil, 4, 6].sort_by { |i| [i ? 1 : 0, i] }
=> [nil, nil, nil, 1, 2, 3, 4, 5, 6, 7]
irb> [2, 5, 1, nil, 7, 3, nil, nil, 4, 6].sort_by { |i| [i ? 0 : 1, i] }
=> [1, 2, 3, 4, 5, 6, 7, nil, nil, nil]