Last active
June 25, 2016 13:10
-
-
Save joshuapaling/431af6d99381cbe41420c6c4dce0fb3e to your computer and use it in GitHub Desktop.
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 | |
def to_roman | |
# Roman numeral problem described in Sandi Metz's newsletter: | |
# http://us3.campaign-archive2.com/?u=1090565ccff48ac602d0a84b4&id=24e2bac263&e=6df8a5006fa | |
# You don't need conditionals, and you don't need two steps either. | |
# The trick: there's nothing special about the subtractive cases. | |
# Treat them as a single numeral that just happens to be two | |
# characters rather than one. | |
all_numerals = { | |
'I' => 1, | |
'IV' => 4, | |
'V' => 5, | |
'IX' => 9, | |
'X' => 10, | |
'XL' => 40, | |
'L' => 50, | |
'XC' => 90, | |
'C' => 100, | |
'CD' => 400, | |
'D' => 500, | |
'CM' => 900, | |
'M' => 1000 | |
} | |
remainder = self | |
result = '' | |
all_numerals.reverse_each do |letter_value, integer_value| | |
quotient, remainder = remainder.divmod(integer_value) | |
result += letter_value * quotient | |
end | |
return result | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment