Skip to content

Instantly share code, notes, and snippets.

@zdzolton
Created August 2, 2013 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zdzolton/6143926 to your computer and use it in GitHub Desktop.
Save zdzolton/6143926 to your computer and use it in GitHub Desktop.
Hacking Roman Numeral support onto Ruby numbers...
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