Sha256: 1c25b37dcbc4e57d927690df7fab9a5cb28fd23a7abad73069fe28e6424f1202

Contents?: true

Size: 1009 Bytes

Versions: 6

Compression:

Stored size: 1009 Bytes

Contents

# frozen_string_literal: true

module Lcms
  module Engine
    class RomanNumerals
      ROMAN_NUMERALS_RE = /^(M|CM|D|CD|C|XC|L|XL|X|IX|V|IV|I)/
      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

      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

      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
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
lcms-engine-0.1.4 app/entities/lcms/engine/roman_numerals.rb
lcms-engine-0.3.0 app/entities/lcms/engine/roman_numerals.rb
lcms-engine-0.1.3 app/entities/lcms/engine/roman_numerals.rb
lcms-engine-0.2.0 app/entities/lcms/engine/roman_numerals.rb
lcms-engine-0.1.2 app/entities/lcms/engine/roman_numerals.rb
lcms-engine-0.1.0 app/entities/lcms/engine/roman_numerals.rb