Created
August 2, 2013 22:17
-
-
Save zdzolton/6143926 to your computer and use it in GitHub Desktop.
Hacking Roman Numeral support onto Ruby numbers...
This file contains 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 Fixnum | |
NUMERALS = { | |
1000 => %w(M), | |
100 => %w(C D), | |
10 => %w(X L), | |
1 => %w(I V), | |
} | |
def to_roman | |
raise "Out of range" unless (1...3000).include?(self) | |
[1000, 100, 10, 1].reduce('') do |out, decimal_position| | |
out + _numerals_for(decimal_position) | |
end | |
end | |
def _numerals_for(decimal_position) | |
one, five = NUMERALS[decimal_position] | |
multiple = (self % (decimal_position * 10)) / decimal_position | |
case multiple | |
when 0..3 | |
one * multiple | |
when 4 | |
one + five | |
when 5..8 | |
five + one * (multiple - 5) | |
when 9 | |
ten = NUMERALS[decimal_position * 10].first | |
one + ten | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment