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).
sort_by works by creating what you can think of as an invisible hash. When called on an array, it calculates a set of numerical keys (known as “sort keys”), and assigns each element in the array to one of those sort keys. Then, the keys are sorted, and mapped back onto the original values.
To sort a hash in Ruby without using custom algorithms, we will use two sorting methods: the sort and sort_by. Using the built-in methods, we can sort the values in a hash by various parameters.
You can use the sort method on an array, hash, or another Enumerable object & you'll get the default sorting behavior (sort based on <=> operator) You can use sort with a block, and two block arguments, to define how one object is different than another (block should return 1, 0, or -1)
[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]
#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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With