9

This is not a trick question:

[1,2,3].sort_by { |x, y| x <=> y }
=> [1, 2, 3] 

[1,2,3].sort_by { |x, y| y <=> x }
=> [1, 2, 3] 

What's going on here? I would have expected the arrays to be opposite one another (as they are with sort and the same parameters).

3

2 Answers 2

20

#sort_by should just take one block parameter, an item from the array, and sorts based on the result of the block.

When passing it two block parameters, the second is set to nil and thus all block results are like 1 <=> nil which is nil so the order of the array is unchanged.

[1, 3, 2].sort_by { |x| x } # sorts using x <=> y
=> [1, 2, 3]

[1, 3, 2].sort_by { |x, y| x <=> y } # sorts using nil <=> nil
=> [1, 3, 2]
1
  • Ah yes Ruby blocks are like Ruby procs - they are not strict with num of arguments passed. If they were OP would error out immediately which I think is much better.
    – Joel Blum
    Jun 16, 2022 at 17:38
6
[1, 3, 2].sort_by { |x| x }
=> [1, 2, 3] 

[1, 3, 2].sort_by { |x| -x }
=> [3, 2, 1] 

[1, 3, 2].sort
=> [1, 2, 3] 

[1, 3, 2].sort.reverse
=> [3, 2, 1] 

[1, 3, 2].sort { |x, y| x <=> y }
=> [1, 2, 3] 

[1, 3, 2].sort { |x, y| y <=> x }
=> [3, 2, 1] 
1
  • Duh...I meant to pass the block to sort, not sort_by -- which, instead of failing noisily does all sorts of unusual things, especially if you're sorting objects (as I was in my actual code). Your answer was right (and first) but I picked @looby's because he pointed out that y = nil
    – Chris B
    Jun 18, 2013 at 23:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.