Project

General

Profile

Actions

Bug #22608

open

Enumerable#sort_by ignores Integer#<=> or Float#<=> redefined in the block

Bug #22608: Enumerable#sort_by ignores Integer#<=> or Float#<=> redefined in the block

Added by sferik (Erik Berlin) about 3 hours ago. Updated about 3 hours ago.

Status:
Open
Assignee:
-
Target version:
-
ruby -v:
ruby 4.1.0dev (2026-11-19T13:09:31Z master 1e71e987c2) +PRISM [arm64-darwin27]
[ruby-core:127626]

Description

Enumerable#sort_by ignores a redefinition of Integer#<=> or Float#<=> that happens while the block is running, when every key is an Integer or every key is a Float.

redefined = false
[3, 1, 2, 5, 4].sort_by do |x|
  unless redefined
    redefined = true
    class Integer
      alias_method :orig_cmp, :<=>
      def <=>(other) = -orig_cmp(other)
    end
  end
  x
end
#=> [1, 2, 3, 4, 5]

I expect [5, 4, 3, 2, 1], which is what sort_by returns when Integer#<=> is redefined before the call, and what it returned in Ruby 3.2. The keys are compared after the block has been called for every element, so the redefinition is already in effect by then. Array#sort_by! and Float keys behave the same way.

This started in Ruby 3.3 with the direct comparison of primitive keys from [Feature #19643]. enum_sort_by checks whether <=> is redefined for Integer and Float before it calls the block, and uses that result to decide whether to compare the keys directly or by calling <=>. A redefinition inside the block comes after the check, so it is never seen.

Actions

Also available in: PDF Atom