<=>
<=>(p1)
public
Comparison—Returns -1 if other_str is less than, 0 if other_str is equal to, and +1 if other_str is greater than str. 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. If the variable $= is false, the comparison is based on comparing the binary values of each character in the string. In older versions of Ruby, setting $= allowed case-insensitive comparisons; this is now deprecated in favor of using String#casecmp.
<=> 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
Case-insensitive comparison
For a case-insensitive comparison, use String#casecmp
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)