Skip to content

Instantly share code, notes, and snippets.

@ltello
Created July 24, 2012 15:13
Show Gist options
  • Save ltello/3170585 to your computer and use it in GitHub Desktop.
Save ltello/3170585 to your computer and use it in GitHub Desktop.
Integers Roman notation
class Fixnum
# Returns the corresponding roman notation for numbers < 1000. Nice message otherwise.
def to_roman
return "Who knows, my friend!!" unless (1...1000) === self
[].tap do |result|
reverse_figures.each_with_index do |figure, weight|
result << figure.send(:to_roman_by_weight, weight)
end
end.reverse.join
end
private
# Constant to map decimal units, tens and cents to roman notation.
ROMAN_CONVERTER = [['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'], # units,
['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'], # tens,
['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'] # cents
]
# Returns the roman notation of self based in weight (units = 0, tens = 1, cents = 2)
def to_roman_by_weight(weight)
ROMAN_CONVERTER[weight][self] if (0..9) === self
end
# Returns a list of the figures of self in reverse order (units first)
def reverse_figures
to_s.split('').reverse.map(&:to_i)
end
end
(-1..1000).each {|d| puts "#{d} - #{d.to_roman}"} and true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment