It is hard to believe that nowadays one would prefer Wikipedia to lookup answers on this kind of question. Ruby has a great documentation: String#<=>
.
By clicking on “toggle source” in the upper right corner of this description, one might easily see that the “default” comparison is being done with rb_str_cmp
, which is apparently using “lexicographical order” for sorting.
On the other hand, <=>
operator is used in all the Comparable
scenarios, hence there is a possibility to easily modify sort behaviour for string lists:
class String
def <=> other
other = other.to_s unless other.is_a? String # or raise an exception
self.length <=> other.length
end
end
["War & Peace", "Zoo", "Aleph", "The Nest of Gentry"].sort
#⇒ ["Zoo", "Aleph", "War & Peace", "The Nest of Gentry"]
In the latter example sorting is being done by the length.