Project

General

Profile

Bug #11907

Updated by barelyknown (Sean Devine) over 8 years ago

**TL;DR Arrays with more than 6 items do not have their order preserved if sorted with sort_by and the sort_by block returns the same value for each.** 

 Let’s start with a simple array of 6 items and sort it by the same value using the sort_by method. In Ruby 2.3 and Ruby 2.2.3, the order of the list will remain the same. 

 ``` 
 list = [1,2,3,4,5,6] 
 list.sort_by { |item| nil } 
 => [1,2,3,4,5,6] 
 ``` 

 But, let’s add one item. 

 ``` 
 list = [1,2,3,4,5,6,7] 

 # with Ruby 2.2.3 
 list.sort_by { |item| nil } 
 => [1, 2, 3, 4, 5, 6, 7] 6] 

 # with Ruby 2.3.0 
 list.sort_by { |item| nil } 
 => [4, 2, 3, 1, 5, 6, 7] 
 ``` 

 Whoa! In Ruby 2.3, the order of the first and fourth items will be swapped. And, if we have a list of 8 or more items, the order of the first and last items will be swapped. 

 ``` 
 list = [1,2,3,4,5,6,7,8] 
 list.sort_by { |item| nil } 
 => [8, 2, 3, 4, 5, 6, 7, 1] 
 ```

Back