Repository navigation
Numeric#<=> returns nil unless the receiver is the argument - #3263
Merged
Merged
Conversation
`Numeric#<=>` returns 0 when `other` is the receiver and nil otherwise, as the comment above the signature says, but the return type was `Integer`. Use `Integer?`, and add a test for both cases.
Collaborator
ksss
approved these changes
Oct 27, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Numeric#<=>returns 0 when the argument is the receiver itself and nil for anything else, as the RDoc comment above the signature says ("zero or nil"). The return type wasInteger, which leaves out the nil case:This changes the return type to
Integer?and addsNumericInstanceTest#test_op_cmpfor both results. With the current signature the new test fails on thenilcase ("Call trace does not match one of method definitions"); withInteger?the Numeric tests pass, and so do the Integer, Float, Rational, Complex and Comparable tests (Ruby 4.0.9).rbs validateand rubocop pass.The only values this implementation returns are 0 and nil, so
0?would also be accurate, likeKernel#<=>since #1945. This usesInteger?because the subclasses in core already do:Float#<=>andComplex#<=>returnInteger?, andInteger#<=>/Rational#<=>returnInteger?for an untyped argument. It also stays compatible with #3210, which discusses whether<=>that subclasses override should be typed asInteger?. It can be changed to0?if that is preferred.