Skip to content

Instantly share code, notes, and snippets.

@joker1007
Created April 25, 2012 15:09
Show Gist options
  • Save joker1007/2490457 to your computer and use it in GitHub Desktop.
Save joker1007/2490457 to your computer and use it in GitHub Desktop.
Fixnum convert to Roman Number String
class Fixnum
def to_roman
return "" unless (1..3999).include?(self)
digit_count = Math.log(self, 10).to_i
case digit_count
when 0
minor = "I"
major = "V"
next_minor = "X"
when 1
minor = "X"
major = "L"
next_minor = "C"
when 2
minor = "C"
major = "D"
next_minor = "M"
when 3
minor = "M"
major = "?"
next_minor = "?"
end
if digit_count > 0
first_digit = self / 10 ** digit_count
next_number = self - first_digit * 10 ** digit_count
else
first_digit = self
next_number = 0
end
mod = first_digit % 10
if mod == 9
roman = "#{minor}#{next_minor}"
elsif mod == 4
roman = "#{minor}#{major}"
elsif mod >= 5
roman = "#{major}" + "#{minor}" * (mod - 5)
else
roman = "#{minor}" * mod
end
return roman + next_number.to_roman
end
end
describe "Fixnum#to_roman" do
shared_examples "should return roman string" do |num, roman|
context "#{num}" do
subject {num}
its(:to_roman) { should == roman }
end
end
it_behaves_like "should return roman string", 1, "I"
it_behaves_like "should return roman string", 2, "II"
it_behaves_like "should return roman string", 5, "V"
it_behaves_like "should return roman string", 4, "IV"
it_behaves_like "should return roman string", 9, "IX"
it_behaves_like "should return roman string", 10, "X"
it_behaves_like "should return roman string", 12, "XII"
it_behaves_like "should return roman string", 801, "DCCCI"
it_behaves_like "should return roman string", 1999, "MCMXCIX"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment