Ion*_*Br. 3 ruby character-encoding iconv
我知道Iconv用于转换字符串的编码.根据我的理解,Kconv也是出于同样的目的(我错了吗?).
我的问题是:它们之间有什么区别,我应该用什么来编码转换.
btw发现了一些信息,即Iconv将从1.9.3版本弃用.
正如/sf/users/1655461/所说,它看起来Kconv像是Iconv专门用于汉字("现代日语书写系统中使用的标识汉字和平假名" http://en.wikipedia .org/wiki/Kanji).除非你正在做一些特别的日语,我猜你不需要Kconv.
如果您使用的是Ruby 1.9,则可以在大多数情况下使用内置编码支持而不是Iconv.我试了几个小时才明白我在做什么,直到我读到这个:
http://www.joelonsoftware.com/articles/Unicode.html
然后你可以开始使用像
String#encode # Ruby 1.9
String#encode! # Ruby 1.9
String#force_encoding # Ruby 1.9
Run Code Online (Sandbox Code Playgroud)
有信心.如果您有更复杂的需求,请阅读http://blog.grayproductions.net/categories/character_encodings
更新感谢JohnZ的评论
Iconv在Ruby 1.9中仍然有用,因为它可以音译字符(某些东西String#encode不能这样做).以下是如何String使用音译为UTF-8的函数进行扩展的示例:
require 'iconv'
class ::String
# Return a new String that has been transliterated into UTF-8
# Should work in Ruby 1.8 and Ruby 1.9 thanks to http://po-ru.com/diary/fixing-invalid-utf-8-in-ruby-revisited/
def as_utf8(from_encoding = 'UTF-8')
::Iconv.conv('UTF-8//TRANSLIT', from_encoding, self + ' ')[0..-2]
end
end
"foo".as_utf8 #=> "foo"
"foo".as_utf8('ISO-8859-1') #=> "foo"
Run Code Online (Sandbox Code Playgroud)
谢谢JohnZ!
| 归档时间: |
|
| 查看次数: |
1379 次 |
| 最近记录: |