In a coding challenge I recently attempted, I found this as an alternative solution to converting numbers to Roman numerals. I don't really understand how this code works. I just figured out what divmod
does but else, I am very confused.
class Integer
def to_roman
roman_arr = {
1000 => "M",
900 => "CM",
500 => "D",
400 => "CD",
100 => "C",
90 => "XC",
50 => "L",
40 => "XL",
10 => "X",
9 => "IX",
5 => "V",
4 => "IV",
1 => "I"
}
num = self
roman_arr.reduce("") do |res, (arab, roman)|
whole_part, num = num.divmod(arab)
res << roman * whole_part
end
end
end
CXX Roman Numerals in numbers is 120.
Numeral. A Roman numeral representing the number twenty-nine (29).
LVI = 56. Hence, the value of Roman Numerals LVI is 56.
reduce / fold is the functional programming equivalent to the looping constructs found in imperative languages. ruby is capable of both.
foo.reduce("") { |a, i| a + i }
is equivalent to
a = ""
foo.each {|i| a = a + i}
a
the num = self
line saves the instance (the number which receives the to_roman
method) in a local variable so you can use it in the block that you pass to reduce.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With