I am just trying to understand the Ruby sort function and the blocks, and I came up with the following code:
a = [1,2,3]
a.sort do |x,y|
x
end
Won’t the returning x be taken as the factor to sort the two elements? I expect the following behaviour:
1,2get passed as block parameters,1is returned.2,3get passed as block parameters,2is returned.1,3get passed as block parameters,3is returned.
So considering the returned values, won’t the sorted array still be [1,2,3]? Where am I getting it wrong?
The block needs to return
-1,0, or1. I don’t believe there are any guarantees about the order the values get passed in. Since you are not honoring the contract with your return value, the result is undefined.In reality, what I believe is happening is that you are always returning a positive value, so the second (later in the array) value is always moved forward. But again, that’s not guaranteed according to the documentation.
This behaves more or less like your description: