From: "sferik (Erik Berlin) via ruby-core" Date: 2026-11-19T16:26:14+00:00 Subject: [ruby-core:127626] [Ruby Bug#22608] Enumerable#sort_by ignores Integer#<=> or Float#<=> redefined in the block Issue #22608 has been reported by sferik (Erik Berlin). ---------------------------------------- Bug #22608: Enumerable#sort_by ignores Integer#<=> or Float#<=> redefined in the block https://bugs.ruby-lang.org/issues/22608 * Author: sferik (Erik Berlin) * Status: Open * ruby -v: ruby 4.1.0dev (2026-11-19T13:09:31Z master 1e71e987c2) +PRISM [arm64-darwin27] * Backport: 3.3: UNKNOWN, 3.4: UNKNOWN, 4.0: UNKNOWN ---------------------------------------- `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. ```ruby 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. -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/