Created
February 10, 2015 18:04
-
-
Save havenwood/8e6a3bfd53854634f298 to your computer and use it in GitHub Desktop.
Example of Comparable with Roshambo
This file contains hidden or 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 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