T.Def T.Def - 2 months ago 25
Ruby Question

Roman Numerals in Ruby

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

Answer

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.