Sha256: 50c56cccb159ac5fcbb14b373203056885c70c7717ac2015c035eeeec27e1f54

Contents?: true

Size: 1012 Bytes

Versions: 9

Compression:

Stored size: 1012 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)/.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

      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

9 entries across 9 versions & 1 rubygems

Version Path
lcms-engine-0.5.5 app/entities/lcms/engine/roman_numerals.rb
lcms-engine-0.5.4 app/entities/lcms/engine/roman_numerals.rb
lcms-engine-0.5.3 app/entities/lcms/engine/roman_numerals.rb
lcms-engine-0.5.2 app/entities/lcms/engine/roman_numerals.rb
lcms-engine-0.5.1 app/entities/lcms/engine/roman_numerals.rb
lcms-engine-0.5.0 app/entities/lcms/engine/roman_numerals.rb
lcms-engine-0.4.2 app/entities/lcms/engine/roman_numerals.rb
lcms-engine-0.4.1 app/entities/lcms/engine/roman_numerals.rb
lcms-engine-0.4.0 app/entities/lcms/engine/roman_numerals.rb