Skip to content

Instantly share code, notes, and snippets.

@lantoli
Created January 17, 2011 13:14
Show Gist options
  • Save lantoli/782827 to your computer and use it in GitHub Desktop.
Save lantoli/782827 to your computer and use it in GitHub Desktop.
roman numerals in ruby using inject
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
}
describe "Roman numerals normal implementation. " do
TRANSFORMATIONS.each do |roman, arabic|
it "transforms #{arabic} to #{roman}" do
arabic.to_roman.should == roman.to_s
end
end
end
describe "Roman numerals old implementation. " do
TRANSFORMATIONS.each do |roman, arabic|
it "transforms #{arabic} to #{roman}" do
arabic.to_roman_old.should == roman.to_s
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment