ruby字符串的encoding,force_encoding,encode,encode!转码(编码转换)

ruby1.9开始对字符串编码支持已经比较完善,我们可以直接通过使用String类的实例方法encodingforce_encoding, encode, encode!进行相关的编码操作。

 学习记录用。转载自网络,详细看参考链接

encoding

ruby1.9中为每个字符串对象增加了encoding信息

1
2
3
1.9.3p392 :001 > '我还是不懂'.encoding
 => #<Encoding:UTF-8>
1.9.3p392 :002 >

  

force_encoding

某些情况下这个附加编码信息可能不正确我们可以修正它

1
2
3
4
5
6
7
8
9
10
11
12
13
1.9.3p392 :011 > x='我还是不懂'
 => "我还是不懂"
1.9.3p392 :012 > x.encoding
 => #<Encoding:UTF-8>
1.9.3p392 :013 > x.bytes.to_a
 => [230, 136, 145, 232, 191, 152, 230, 152, 175, 228, 184, 141, 230, 135, 130]
1.9.3p392 :014 > x.force_encoding 'gbk'
 => "\x{E688}\x{91E8}\x{BF98}\x{E698}\x{AFE4}\x{B88D}\x{E687}\x82"
1.9.3p392 :015 > x.encoding
 => #<Encoding:GBK>
1.9.3p392 :016 > x.bytes.to_a
 => [230, 136, 145, 232, 191, 152, 230, 152, 175, 228, 184, 141, 230, 135, 130]
1.9.3p392 :017 >

  

注意:force_encoding方法只是改变了字符串对象的编码信息,并没有改变字符串对象实际存储的内容。

 

encode、encode!

在ruby1.9之前如我我们需要编码转换则需要使用一些外部库, 现在我们可以直接使用String对象的实例方法encode, encode!进行操作

1
2
3
4
5
encode(encoding [, options] ) → str click to toggle source
encode(dst_encoding, src_encoding [, options] ) → str
encode([options]) → str
encode!(encoding [, options] ) → str click to toggle source
encode!(dst_encoding, src_encoding [, options] ) → str

  

详细的api请参考这里

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1.9.3p392 :009 > x='我还是不懂'
 => "我还是不懂"
1.9.3p392 :010 > x.encoding
 => #<Encoding:UTF-8>
1.9.3p392 :011 > x.bytes.to_a
 => [230, 136, 145, 232, 191, 152, 230, 152, 175, 228, 184, 141, 230, 135, 130]
1.9.3p392 :012 > y=x.encode 'gbk','utf-8'
 => "\x{CED2}\x{BBB9}\x{CAC7}\x{B2BB}\x{B6AE}"
1.9.3p392 :013 > y.encoding
 => #<Encoding:GBK>
1.9.3p392 :014 > y.bytes.to_a
 => [206, 210, 187, 185, 202, 199, 178, 187, 182, 174]
1.9.3p392 :015 > x.encode! 'gbk','utf-8'
 => "\x{CED2}\x{BBB9}\x{CAC7}\x{B2BB}\x{B6AE}"
1.9.3p392 :016 > x.encoding
 => #<Encoding:GBK>
1.9.3p392 :017 > x.bytes.to_a
 => [206, 210, 187, 185, 202, 199, 178, 187, 182, 174]
1.9.3p392 :018 >

  

可以看到encode改变了编码信息同时也改变了字符串对象存储的内容

 参考 :http://blog.bccn.net/%E9%9D%99%E5%A4%9C%E6%80%9D/15131

总结

  • encdoing用来查看字符串的编码信息。
  • force_encoding用来修正字符串编码信息,注意是修正。
  • encodeencode!用来转码字符串。
posted @   鞋带松了  阅读(366)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示