简单的字符串转换到Ruby 1.8中的UTF-8 [英] Simple Conversion Of String To UTF-8 in Ruby 1.8

查看:266
本文介绍了简单的字符串转换到Ruby 1.8中的UTF-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Ruby 1.9中,你可以轻松地重新编码一个这样的字符串。

I know that in Ruby 1.9 you can easily re-encode a string like this.

s = s.encode('UTF-8')

Ruby 1.8中的等效项是什么?

What is the equivalent in Ruby 1.8? What require lines does it need.

我看到的所有教程都是不必要的复杂,我不明白发生了什么。

All the tutorials I have seen are needlessly complicated and I don't understand what is going on.

推荐答案

James Edward Gray II有详细的帖子集合,处理Ruby 1.8中的编码和字符集问题。标题为使用iconv 进行编码转换的帖子包含详细信息。

James Edward Gray II has a detailed collections of posts dealing with encoding and character set issues in Ruby 1.8. The post entitled Encoding Conversion with iconv contains detailed information.

摘要: iconv gem将转换编码的所有工作。确保其安装有:

Summary: the iconv gem does all the work of converting encodings. Make sure it's installed with:

gem install iconv

现在,你需要知道你的字符串的编码是什么,因为Ruby 1.8将字符串视为一个字节数组(没有固有编码)。例如,你的字符串是在latin1,你想将其转换为utf-8

Now, you need to know what encoding your string is currently in as Ruby 1.8 treats Strings as an array of bytes (with no intrinsic encoding.) For example, say your string was in latin1 and you wanted to convert it to utf-8

require 'iconv'

string_in_utf8_encoding = Iconv.conv("UTF8", "LATIN1", string_in_latin1_encoding)

参数顺序为:


  1. 目标编码

  2. 源编码

  3. 要转换的字符串

这篇关于简单的字符串转换到Ruby 1.8中的UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆