Method: ChineseNumber::Parser#parse

Defined in:
lib/chinese_number/parser.rb

#parse(word) ⇒ Object

Raises:



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/chinese_number/parser.rb', line 48

def parse word
  
  raise InvalidWord unless word =~ /\A#{TOKEN}\Z/

  # 类似“二零一二” 这种短语,可以直接拼数字返回
  unless word =~ MULTIPER_TOKEN
    return word.gsub(/\S/) {|w| DIGIT_MAP[w]}.to_i
  end

  @scanner = StringScanner.new( word )
  @parts   = []

  while w = @scanner.scan( /\S/ )
    case w
    when ARABIC_NUMBER
      if @scanner.check(ARABIC_NUMBER)
        w << @scanner.scan( /\d+/ )
        handle_digit w.to_i
      else
        handle_digit DIGIT_MAP[w]
      end
    when DIGIT_TOKEN
      handle_digit DIGIT_MAP[w]
    when MULTIPER_TOKEN
      handle_multiper MULTIPERS[w]
    else
      raise UnexpectToken.new(w)
    end
  end

  parts.reduce(0) do |sum, part|
    sum + part.to_i
  end
end