Class: Lcms::Engine::RomanNumerals

Inherits:
Object
  • Object
show all
Defined in:
app/entities/lcms/engine/roman_numerals.rb

Constant Summary collapse

ROMAN_NUMERALS_RE =
/^(M|CM|D|CD|C|XC|L|XL|X|IX|V|IV|I)/.freeze
SYMBOLS =
[
  [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']
].freeze

Class Method Summary collapse

Class Method Details

.from_roman(roman) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/entities/lcms/engine/roman_numerals.rb', line 34

def self.from_roman(roman)
  value = 0
  str = roman.upcase

  while (m = str.match(ROMAN_NUMERALS_RE))
    # add the arabic number for the matched numeral
    value += SYMBOLS.detect { |pair| pair[1] == m[1] }.first
    str = m.post_match
  end

  value
end

.to_roman(num) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'app/entities/lcms/engine/roman_numerals.rb', line 23

def self.to_roman(num)
  [].tap do |roman|
    SYMBOLS.each do |arab, rom|
      while num >= arab
        roman << rom
        num -= arab
      end
    end
  end.join
end