Flowdock
<=>(p1) public

Comparison—Returns -1, 0, +1, or nil depending on whether string is less than, equal to, or greater than other_string.

nil is returned if the two values are incomparable.

If the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered greater than the shorter one.

<=> is the basis for the methods <, <=, >, >=, and between?, included from module Comparable. The method String#== does not use Comparable#==.

"abcdef" <=> "abcde"     #=> 1
"abcdef" <=> "abcdef"    #=> 0
"abcdef" <=> "abcdefg"   #=> -1
"abcdef" <=> "ABCDEF"    #=> 1
"abcdef" <=> 1           #=> nil
Show source
Register or log in to add new notes.
October 9, 2009
0 thanks

Case-insensitive comparison

For a case-insensitive comparison, use String#casecmp

June 25, 2010
0 thanks

can return nil

I was surprised to get nil back when the right hand side (RHS) was nil. (I was expecting an exception.)

>> "abc" <=> nil
=> nil

Looking at the source I find you’ll get nil back in several cases when the RHS isn’t a string.

  • If the RHS doesn’t implement to_str.

  • If the RHS doesn’t implement <=>.

Assuming the RHS does implement to_str and <=>, the code delegates to the RHS and negates the result:

return - (rhs <=> self)