# encoding: utf-8
class String

  def to_pinyin
    h = Hash.new
    idx_file_path = File.expand_path('../../data/idx99-tone.txt',__FILE__)
    open(idx_file_path,'r').each do |line|
      a = line.gsub("\n","").split("\t")
      h.store a[0], a[1]
    end
    result = ""
    self.scan(/./) do |char|
      if h[char]
        result = result + h[char] + " "
      else
        result = result + char
      end
    end
    return result.rstrip
  end

end

# encoding: utf-8
class String

  def to_pinyin
    idx_file_path = File.expand_path('../../data/idx99-tone.txt',__FILE__)
    result = ""
    self.scan(/./) do |char|
      match = %x[grep -m1 '^#{char}' #{idx_file_path}]
      if match.empty?
        result = result + char
      else
        pinyin =  match.gsub("\n","").split("\t")[1]
        result = result + pinyin + " "
      end
    end
    return result.rstrip
  end
      
end

Switch to a more efficient grep based search method
Switch to a more efficient grep based search method
