Spaceship Operator
The <=>
operator is known as the spaceship operator. By convention, this method is how many Ruby classes define how instances can be compared and sorted relative to one another.
> require 'securerandom'
=> true
> SecureRandom.hex(10)
=> "f9932bb9aabadbd528b5"
irb(main):182> arr = SecureRandom.hex(10).split('')
=> ["e", "8", "0", "0", "e", "f", "4", "8", "2", "2", "5", "f", "c", "5", "c", "6", "9", "b", "f", "4"]
irb(main):183> arr.sort
=> ["0", "0", "2", "2", "4", "4", "5", "5", "6", "8", "8", "9", "b", "c", "c", "e", "e", "f", "f", "f"]
The reason this #sort
is able to work is because String#<=>
informs the sort that "9"
is greater than "0"
, but is less than "f"
.