Project

General

Profile

Actions

Bug #11907

closed

sort_by does not preserve order with arrays with 7+ items and a block that returns the same value

Added by barelyknown (Sean Devine) over 8 years ago. Updated almost 5 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:72552]

Description

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]

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

Updated by barelyknown (Sean Devine) over 8 years ago

  • Description updated (diff)

Updated by sawa (Tsuyoshi Sawada) over 8 years ago

I am pretty sure this proposal will be rejected. Ruby's sort is not stable. If you want to do stable sort, use with_index.

Actions #3

Updated by jeremyevans0 (Jeremy Evans) almost 5 years ago

  • Status changed from Open to Rejected
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0