nik7
nik7

Reputation: 3058

Understanding sort method and in general blocks in ruby

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. 1,2 get passed as block parameters, 1 is returned.
  2. 2,3 get passed as block parameters, 2 is returned.
  3. 1,3 get passed as block parameters, 3 is returned.

So considering the returned values, won't the sorted array still be [1,2,3]? Where am I getting it wrong?

Upvotes: 1

Views: 152

Answers (1)

Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34031

The block needs to return -1, 0, or 1. 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:

a = [1,2,3]
a.sort do |x,y|
  x <=> y
end

Upvotes: 7

Related Questions