Skip to content

Instantly share code, notes, and snippets.

@mdesantis
Created July 23, 2012 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdesantis/3164520 to your computer and use it in GitHub Desktop.
Save mdesantis/3164520 to your computer and use it in GitHub Desktop.
Circular comparison in Ruby
class RockPaperScissors
ITEMS = %W(A P B N)
def self.compare(item, other_item)
new(item).compare other_item
end
def initialize(item)
# input validations?
@item = item
end
def compare(other_item)
# input validations?
indexes_subtraction = ITEMS.index(@item) - ITEMS.index(other_item)
case indexes_subtraction
when 1, -1
- indexes_subtraction
else
indexes_subtraction <=> 0
end
end
end
require 'test/unit'
include MiniTest::Assertions
assert_equal RockPaperScissors.compare('A', 'A'), 0
assert_equal RockPaperScissors.compare('P', 'P'), 0
assert_equal RockPaperScissors.compare('B', 'B'), 0
assert_equal RockPaperScissors.compare('N', 'N'), 0
assert_equal RockPaperScissors.compare('A', 'P'), 1
assert_equal RockPaperScissors.compare('P', 'A'), -1
assert_equal RockPaperScissors.compare('P', 'B'), 1
assert_equal RockPaperScissors.compare('B', 'P'), -1
assert_equal RockPaperScissors.compare('B', 'N'), 1
assert_equal RockPaperScissors.compare('N', 'B'), -1
assert_equal RockPaperScissors.compare('N', 'A'), 1
assert_equal RockPaperScissors.compare('A', 'N'), -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment