class String

Constants

TEN_NUMERALS
UNITS_GREATER_THAN_TEN_THOUSAND

Public Instance Methods

to_arabic_numeral() click to toggle source
# File lib/convert_numeral.rb, line 80
def to_arabic_numeral
  sentence_from_one_to_thousand = '(?:[一二三四五六七八九]?千)?(?:[二三四五六七八九]?百)?(?:[二三四五六七八九]?十)?(?:[零一二三四五六七八九])?'
  sentence = UNITS_GREATER_THAN_TEN_THOUSAND.map { |unit| "(#{sentence_from_one_to_thousand}#{unit})?" }.reverse.join
  regexp = Regexp.new(sentence)

  first_matches = scan(regexp).first.reverse

  first_matches.each_with_index.inject(0) do |current_total, (first_match, first_match_s_index)|
    if !first_match.nil?
      matches = first_match.scan(/([一二三四五六七八九]?千)?([二三四五六七八九]?百)?([二三四五六七八九]?十)?([零一二三四五六七八九])?/).first.reverse
      sum = matches.each_with_index.inject(0) do |current_sum, (match, index)|
        numeral = match&.slice(/[零一二三四五六七八九]/)
        
        if match.nil?
          current_sum
        elsif numeral.nil?
          current_sum + (10 ** (index))
        else
          current_sum + ((10 ** (index)) * TEN_NUMERALS.index(numeral))
        end
      end

      current_total + (sum * (10 ** (4 * first_match_s_index)))
    else
      current_total
    end
  end
end