Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created February 10, 2015 18:04
Show Gist options
  • Save havenwood/8e6a3bfd53854634f298 to your computer and use it in GitHub Desktop.
Save havenwood/8e6a3bfd53854634f298 to your computer and use it in GitHub Desktop.
Example of Comparable with Roshambo
class Roshambo
OPTIONS = [:rock, :paper, :scissors]
WINNERS = OPTIONS.rotate.zip(OPTIONS).to_h
LOSERS = WINNERS.invert
attr_reader :value
include Comparable
def initialize value = OPTIONS.sample
unless OPTIONS.include? value
raise ArgumentError, 'invalid hand'
end
@value = value
end
def to_s
@value.to_s.capitalize
end
private
def <=> other
case other.value
when value then 0
when WINNERS[value] then 1
when LOSERS[value] then -1
end
end
end
rock = Roshambo.new :rock
paper = Roshambo.new :paper
scissors = Roshambo.new :scissors
rock == scissors
#=> false
rock > scissors
#=> true
rock < scissors
#=> false
paper < scissors
#=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment