Project

General

Profile

Actions

Bug #16966

closed

Unexpected behavior of sort method

Bug #16966: Unexpected behavior of sort method

Added by kk (Kirill /) over 5 years ago. Updated over 5 years ago.

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

Description

The ruby cook book from 2015 has the following example of using sort method:

[1,100,42,23,26,1000].sort {|x,y| x==42 ? 1 : x<=>y }
# => [1, 23, 26, 100, 10000, 42]

It actually returned [1, 23, 26, 42, 100, 1000].

With a different array, I get the expected result with 42 at the end:

[1,2,42,46,22,33].sort {|x,y| x==42 ? 1 : x<=>y }
# => [1, 2, 22, 33, 46, 42]

Files

Updated by mame (Yusuke Endoh) over 5 years ago Actions #1 [ruby-core:98843]

  • Status changed from Open to Rejected

It is a bug of the book. Please report it to the author :-)

There is no guarantee about which x or y accepts each element. The following code will work as expected.

[1,100,42,23,26,1000].sort {|x,y| x==42 ? 1 : y==42 ? -1 : x<=>y } #=> [1, 23, 26, 100, 1000, 42]

Updated by sawa (Tsuyoshi Sawada) over 5 years ago Actions #2

  • Description updated (diff)
Actions

Also available in: PDF Atom