Last active
December 17, 2015 04:29
-
-
Save kryptykphysh/5551140 to your computer and use it in GitHub Desktop.
Demonstrating the spaceship operator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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