4

我知道 Iconv 用于转换字符串的编码。根据我的理解,Kconv 是出于同样的目的(我错了吗?)。

我的问题是:它们之间有什么区别,我应该使用什么进行编码转换。

顺便说一句,发现一些信息表明 Iconv 将从 1.9.3 版本中弃用。

4

1 回答 1

6

正如https://stackoverflow.com/users/23649/jtbandes所说,它看起来KconvIconv但专门用于汉字(“现代日语书写系统中使用的表意汉字与平假名一起使用” http://en.wikipedia .org/wiki/汉字)。除非您正在专门研究日语,否则我猜您不需要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

有信心的。如果您有更复杂的需求,请阅读http://blog.grayproductions.net/categories/character_encodings

更新感谢评论中的JohnZ

Iconv在 Ruby 1.9 中仍然有用,因为它可以音译字符(这是String#encodeet al. 做不到的)。下面是一个如何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"

谢谢约翰Z!

于 2011-06-26T20:37:02.677 回答