From: ryanflach@... Date: 2019-07-25T22:38:55+00:00 Subject: [ruby-core:93918] [Ruby master Bug#16022] Enumerable#sort_by returns a swapped first and last element when the sort value is identical and collection is >= 8 elements Issue #16022 has been reported by ryanflach (Ryan Flach). ---------------------------------------- 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 * Author: ryanflach (Ryan Flach) * Status: Open * 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: