ruby1.9.2 String中的 encode, encode!, force_encoding.

本文详细解释了Ruby中字符串处理方法#encode与#force_encoding的区别。#encode方法改变字符串的编码而不改变字符内容,适用于需要转换编码场景;而#force_encoding则保持字节不变,可能会导致字符变得无效。

根据 http://yugui.jp/articles/850 这上面说的。

For a StringString#encode keeps the characters but changes the encoding in which the characters are encoded.#encode is not destructive but #encode! is the destructive version. The byte representation of a character is depend on encodingSo #encode and #encode! generally change the byte representation of the string.
#force_encoding in contrarily keeps byte representation but changes charactersAfter #force_encodingsometimesthe string become invalid as a character sequence.
In other words#encode treats a String object as a character sequence but #force_encoding treats it as a bytesequence.

对于String, encode方法 保留字符, 但是当转码成功的时候改变编码,encode! 是 encode 的强制版。
每个字符的字节是根据编码来产生。也就是说,encode 和encode! 通常改变字符串的字节。

相反地,force_encoding方法 保留字节并且可能改变字符,在force_encoding后,一些字符会变成无效的字符序列。

一句话,encode 以字符序列的方式处理 String对象,而force_encoding 以字节序列的方式。

不知道理解的正确不正确,望高手指点。

转载于:https://www.cnblogs.com/zhuyc/archive/2011/09/18/2180511.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值