Created
July 23, 2012 16:19
-
-
Save mdesantis/3164520 to your computer and use it in GitHub Desktop.
Circular comparison in Ruby
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 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