1

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?

1
  • There is another method which uses the return value from the block as a sorting factor, it's called sort_by. Commented Aug 6, 2012 at 7:42

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

3 Comments

is there any strict path in what order x,y values gets passed to the block ? when i use a bigger array like [1,2,3,4,5], the x,y order is (1,3),(3,5),(2,3),(4,3),(2,4),(4,1)
@nlingutla The documentation doesn't specify an order, so I don't consider it safe to count on any specific order. Different implementations (and future versions of the same implementation) may well use a different algorithm.
Interesting... I checked the order which compares are done on my system (running Ruby 1.9.3), and they are a bit different from @nlingutla. It appears that up to 4 elements, a special-purpose sort function which uses a fixed sequence of compares is used. After that, it seems to be using quicksort. I haven't checked the interpreter source -- I'm just guessing from observing the order which compares are done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.