Issue #14017 has been updated by duerst (Martin Drst).


nobu (Nobuyoshi Nakada) wrote:

> Ruby's sort method is not stable sort.
> 
> The documentation of  `Array#sort_by!`:
> > The result is not guaranteed to be stable.  When two keys are equal,
> > the order of the corresponding elements is unpredictable.

Just to be cristal clear:

A sort being stable means that when values are the same, the elements stay in the original order.
This would mean that the order is predictable.
But "the order of the corresponding elements is unpredictable" is stronger, it also inplies that the order can change across versions or implementations, or (at least in theory) across invocations.

----------------------------------------
Bug #14017: Hash.sort_by inconsistent between 2.2.6 and upper versions
https://bugs.ruby-lang.org/issues/14017#change-67258

* Author: chucke (Tiago Cardoso)
* Status: Rejected
* Priority: Normal
* Assignee: 
* Target version: 
* ruby -v: 2.2.6
* Backport: 2.3: UNKNOWN, 2.4: UNKNOWN
----------------------------------------
The bug occurs when sorting by a numeric value and two different keys have similar values: It is very easily demonstrated here:

```ruby
enc = {"foo"=>0.9, "bar"=>1.0, "identity"=>1.0}
enc.sort_by { |_, q| -q }

# in ruby 2.2.6
#=> [["identity", 1.0], ["bar", 1.0], ["foo", 0.9]]
# in rubies > 2.2
#=> [["bar", 1.0], ["identity", 1.0], ["foo", 0.9]]
```

For the record, newer rubies present the correct version IMO, as the order of equivalent values shouldn't be changed based on the same value.

I looked at the [ruby 2.3 release notes](https://github.com/ruby/ruby/blob/v2_3_0/NEWS), but couldn't find the mention to a fix, so I can't say that this is a "behaviour change, upgrade to new" case. What I can say is that this behaviour seems to have changed in ruby 2.3 (tested also with ruby 2.2.2 and ruby 2.1.9 and can reproduce the same result as with 2.2.6). 

As an example of production code which is probably returning a wrong result is rack, which [uses as variation of this to select the best content encoding](https://github.com/rack/rack/blob/911c4fe15e3e57d44ac891c0cbabbf44bdf71201/lib/rack/utils.rb#L188) .

Is this something which can be backported into a possible 2.2.7, or is ruby 2.2 in maintenance mode?



-- 
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>