The subtle difference between sorting and sort_by

This is not a trick:

[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 expect the arrays to be opposite to each other (since they have the sort and the same parameters).

+6
source share
2 answers

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

When passing two parameters of the block, the second is set to nil , and therefore, all results of the block are similar to 1 <=> nil , which is nil , so the order of the array does not change.

 [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] 
+15
source
 [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] 
+5
source

Source: https://habr.com/ru/post/947605/


All Articles