Bug #22608
openEnumerable#sort_by ignores Integer#<=> or Float#<=> redefined in the block
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.