Skip to content

Instantly share code, notes, and snippets.

@amuino
Forked from lantoli/roman_numerals.rb
Created February 3, 2011 23:33
Show Gist options
  • Save amuino/810460 to your computer and use it in GitHub Desktop.
Save amuino/810460 to your computer and use it in GitHub Desktop.
require 'rspec'
class Fixnum
ROMANS = { M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90, L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1 }
def to_roman
remaining_number = self
ROMANS.inject ("") do | roman_str, current_number |
times,remaining_number = remaining_number.divmod current_number[1]
roman_str + current_number[0].to_s * times
end
end
def to_roman_old
roman = ""
ROMANS.inject (self) do | remaining, number |
quotient,rest = remaining.divmod number[1]
roman += number[0].to_s * quotient
rest
end
roman
end
end
TRANSFORMATIONS = {
I: 1, II: 2, III: 3, IV: 4, V: 5, VI: 6, VII: 7, VIII: 8, IX: 9, X: 10, XI: 11, XII: 12, XIV: 14, XV: 15,
XIX: 19, XXXIX: 39, XL: 40, XLI: 41, L: 50, LXXXIX: 89, XC: 90, XCIX: 99, C: 100, CCCXCIX: 399, CD: 400,
D: 500, DCCCXCIX: 899, CM: 900, M: 1000, MMXI: 2011
}
[:to_roman, :to_roman_old].each do |method|
describe "Roman numerals '#{method}' implementation. " do
TRANSFORMATIONS.each do |roman, arabic|
it "transforms #{arabic} to #{roman}" do
arabic.send(method).should == roman.to_s
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment