---
title: "ruby 转化ANSI 编为UTF-8"
author: "pobing"
date: "2012-06-14T14:13:49Z"
tags: []
categories: ["编程语言"]
slug: "ruby-ansi-utf-8"
draft: false
lastmod: "2012-06-14T14:13:49Z"
id: 1560877
url: "https://pobing.iteye.com/blog/1560877"
---

用到：gem： rchardet19，string.encoding,string.force_encoding



```ruby

require 'rchardet19' 


def convert_encode file
    string=File.open(file.location,"r+").read # 
    cd = CharDet.detect(string) 
   # 获取文件编码
   #cd.encoding
    if string.encoding != 'UTF-8' && cd.encoding=="utf-8"
      string.force_encoding('UTF-8') 
    elsif string.encoding != 'UTF-8'
      string.force_encoding('GBK') 
    end
   File.open(file.location, "w") { |f| f.puts string.encode("UTF-8") }
  end
```