Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roman Numerals in Ruby

Tags:

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
like image 959
T.Def Avatar asked Sep 29 '14 04:09

T.Def


People also ask

What number is CXX?

CXX Roman Numerals in numbers is 120.

What number is XXIX Roman?

Numeral. A Roman numeral representing the number twenty-nine (29).

What is LVI in Greek numbers?

LVI = 56. Hence, the value of Roman Numerals LVI is 56.


1 Answers

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.

like image 178
eno3nt Avatar answered Nov 15 '22 06:11

eno3nt