# -*- coding: utf-8 -*-

module PinYin
  module Util
    extend self

    ASCIIMapping = {
      'ā' => ['a', 1], 'ē' => ['e', 1], 'ī' => ['i', 1], 'ō' => ['o', 1], 'ū' => ['u', 1], 'ǖ' => ['v', 1],
      'á' => ['a', 2], 'é' => ['e', 2], 'í' => ['i', 2], 'ó' => ['o', 2], 'ú' => ['u', 2], 'ǘ' => ['v', 2],
      'ǎ' => ['a', 3], 'ě' => ['e', 3], 'ǐ' => ['i', 3], 'ǒ' => ['o', 3], 'ǔ' => ['u', 3], 'ǚ' => ['v', 3],
      'à' => ['a', 4], 'è' => ['e', 4], 'ì' => ['i', 4], 'ò' => ['o', 4], 'ù' => ['u', 4], 'ǜ' => ['v', 4]
    }

    def to_ascii(reading, with_tone=true)
      reading = reading.dup

      ASCIIMapping.each do |char, (ascii, tone)|
        if reading.tr!(char, ascii) && with_tone
          return reading.concat(tone.to_s)
        end
      end

      reading
    end

  end
end

# -*- coding: utf-8 -*-

module PinYin
  module Util
    extend self

    ASCIIMapping = {
      'ā' => ['a', 1], 'ē' => ['e', 1], 'ī' => ['i', 1], 'ō' => ['o', 1], 'ū' => ['u', 1], 'ǖ' => ['v', 1],
      'á' => ['a', 2], 'é' => ['e', 2], 'í' => ['i', 2], 'ó' => ['o', 2], 'ú' => ['u', 2], 'ǘ' => ['v', 2],
      'ǎ' => ['a', 3], 'ě' => ['e', 3], 'ǐ' => ['i', 3], 'ǒ' => ['o', 3], 'ǔ' => ['u', 3], 'ǚ' => ['v', 3],
      'à' => ['a', 4], 'è' => ['e', 4], 'ì' => ['i', 4], 'ò' => ['o', 4], 'ù' => ['u', 4], 'ǜ' => ['v', 4]
    }

    def to_ascii(reading, with_tone=true)
      ASCIIMapping.each do |char, (ascii, tone)|
        if reading.include? char
          if with_tone
            return reading.sub(char, ascii).concat(tone.to_s)
          else
            return reading.sub(char, ascii)
          end
        end
      end
      reading
    end

  end
end

Replace accent character using sub instead of tr
Replace accent character using sub instead of tr

When replace accent character in PinYin with normal English character,
do not use "tr", but use "sub" instead. Because for ruby 1.8, a accent
character is treat as two or more characters and when replace using
"tr", it will be replaced with two or more normal characters.
E.g.

    Input: jiǎ
    Replace with tr:  jiaa3
    Replace with sub: jia3

Signed-off-by: Jiang Xin <61b5e6324abee2d58ba2cf49f31c723faf6fd946@gmail.com>
