Skip to content

Instantly share code, notes, and snippets.

@DataWraith
Created April 6, 2011 13:44
Show Gist options
  • Save DataWraith/905659 to your computer and use it in GitHub Desktop.
Save DataWraith/905659 to your computer and use it in GitHub Desktop.
The result of my 2nd attempt at the Roman Numerals Kata
class Fixnum
ROMAN_CONVERSION = [
[1000, 'M' ],
[900, 'CM'],
[500, 'D' ],
[400, 'CD'],
[100, 'C' ],
[90, 'XC'],
[50, 'L' ],
[40, 'XL'],
[10, 'X' ],
[9, 'IX'],
[5, 'V' ],
[4, 'IV'],
[1, 'I' ]
]
def to_roman
num = self
result = ""
ROMAN_CONVERSION.each do |arabic, roman|
div, num = num.divmod(arabic)
result << roman * div
end
result
end
def self.from_roman(numeral)
num_str = numeral.dup
result = 0
ROMAN_CONVERSION.each do |arabic, roman|
while num_str.start_with?(roman)
num_str.slice!(roman)
result += arabic
end
end
result
end
end
require_relative File.join("..", "lib", "roman_numerals")
TEST_CASES = [
[1, 'I'],
[2, 'II'],
[3, 'III'],
[4, 'IV'],
[5, 'V'],
[6, 'VI'],
[7, 'VII'],
[8, 'VIII'],
[9, 'IX'],
[10, 'X'],
[14, 'XIV'],
[16, 'XVI'],
[19, 'XIX'],
[23, 'XXIII'],
[42, 'XLII'],
[50, 'L'],
[80, 'LXXX'],
[99, 'XCIX'],
[128, 'CXXVIII'],
[438, 'CDXXXVIII'],
[500, 'D'],
[999, 'CMXCIX'],
[1776, 'MDCCLXXVI'],
[1985, 'MCMLXXXV']
]
describe Fixnum, "#to_roman" do
TEST_CASES.each do |arabic, roman|
it "should convert #{arabic} to #{roman}" do
arabic.to_roman.should == roman
end
end
end
describe Fixnum, "#from_roman" do
TEST_CASES.each do |arabic, roman|
it "should convert #{roman} to #{arabic}" do
Fixnum.from_roman(roman).should == arabic
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment