Issue #16022 has been updated by jeremyevans0 (Jeremy Evans).


ryanflach (Ryan Flach) wrote:
> Thanks for the response. You are definitely correct regarding its documentation. What I was attempting to point out was the apparent predictability in which it is not consistent

The sort isn't stable, so the order of elements when the `sort_by` result is equal is not specified. The "predictability in which it is not consistent" is simply due to an implementation detail.  It is not a bug.

Your initial post stated `I would expect the above to remain in order, when a sort has not actually taken place`.  That made it sound like you were expecting a stable sort and you considered the current behavior a bug.  I apologize if I misunderstood and you were attempting to point out an implementation detail and not report a bug.

----------------------------------------
Bug #16022: Enumerable#sort_by returns a swapped first and last element when the sort value is identical and collection is >= 8 elements
https://bugs.ruby-lang.org/issues/16022#change-80054

* Author: ryanflach (Ryan Flach)
* Status: Rejected
* Priority: Normal
* Assignee: 
* Target version: 
* ruby -v: 2.5.5p157
* Backport: 2.5: UNKNOWN, 2.6: UNKNOWN
----------------------------------------
**Overview**
I've seen in the source code that the ordering may be unpredictable (https://github.com/ruby/ruby/blob/515e106fb73a1a3bc69b6f1670bbaaebf45fee30/enum.c#L1159-L1160), but it seems to consistently swap the first and last element when there are 8 or more elements.

**Ruby version**
ruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-darwin18]

**To reproduce:**
``` ruby
[1] pry(main)> [{a: 1, b: 1}, {a: 1, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}, {a: 1, b: 5}, {a: 1, b: 6}, {a: 1, b: 7}, {a: 1, b: 8}].sort_by { |h| h[:a] }
=> [{:a=>1, :b=>8}, {:a=>1, :b=>2}, {:a=>1, :b=>3}, {:a=>1, :b=>4}, {:a=>1, :b=>5}, {:a=>1, :b=>6}, {:a=>1, :b=>7}, {:a=>1, :b=>1}]
[2] pry(main)> [{a: 1, b: 1}, {a: 1, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}, {a: 1, b: 5}, {a: 1, b: 6}, {a: 1, b: 7}].sort_by { |h| h[:a] }
=> [{:a=>1, :b=>1}, {:a=>1, :b=>2}, {:a=>1, :b=>3}, {:a=>1, :b=>4}, {:a=>1, :b=>5}, {:a=>1, :b=>6}, {:a=>1, :b=>7}]

```
I would expect the above to remain in order, when a sort has not actually taken place.




-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>