Skip to content

Instantly share code, notes, and snippets.

@kryptykphysh
Last active December 17, 2015 04:29
Show Gist options
  • Save kryptykphysh/5551140 to your computer and use it in GitHub Desktop.
Save kryptykphysh/5551140 to your computer and use it in GitHub Desktop.
Demonstrating the spaceship operator.
class Cuttlefish
# Because we've defined <=> we can use all the Comparable methods
# http://ruby-doc.org/core-2.0/Comparable.html
include Comparable
attr_reader :name, :ink_capacity
def initialize(name, ink_capacity = 0)
@name = name
@ink_capacity = ink_capacity
end
def <=> (other)
ink_capacity <=> other.ink_capacity
end
end
c1 = Cuttlefish.new('Albert')
c2 = Cuttlefish.new('Bertie', 200)
c3 = Cuttlefish.new('Cyril', 150)
puts c1 > c2 # 0 > 200 => false
puts c3 > c2 # 150 > 200 => false
puts c3.between?(c1, c2) # 150 between 0 and 200 => true
puts [c1, c2, c3].sort.inspect # Sorted in ascending order by :ink_capacity
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment