【问题标题】:Translit equivalent in Ruby 2 (without iconv)Ruby 2 中的等效转换(没有 iconv)
【发布时间】:2015-02-16 11:44:29
【问题描述】:

我们知道,我们可以在 Ruby 1.9.3 中使用 IconvTRANSLIT 标志,它将用它们的 ASCII 等效字符替换重音字符,只有当它们不存在于目标编码中时

使用示例:

require 'iconv'
z = "Håkan"
Iconv.conv("windows-1250//TRANSLIT", "UTF-8", z) 
# => outputs "Hakan" (with diactric removed)
pl = "zażółć"
Iconv.conv("windows-1250//TRANSLIT", "UTF-8", pl)
# => outputs "zażółć" (because windows-1250 contains all this characters)
# well, to be honest it outputs "za\xBF\xF3\xB3\xE6" because of terminal settings
# but I hope you understand

但是 Iconv 已弃用,建议改用 String#encode

但是在使用#encode 时出现问题:

z.encode('windows-1250', 'utf-8')
Encoding::UndefinedConversionError: U+00E5 to WINDOWS-1250 in conversion from UTF-8 to WINDOWS-1250

有没有办法在 Ruby 2+ 中使用 String#encode 来获得类似于带有 iconv TRANSLIT 标志的行为?

【问题讨论】:

  • hm,你的例子在 Ruby 1.9.3-p448 中给了我invalid multibyte char (US-ASCII) syntax error, unexpected $end, expecting ')'
  • 您已经确定这两种方法之间存在差异,但尚未分享差异是什么。您的转换所需的输出是什么?
  • @RustamA.Gasanov - 我已经让示例更简单了,也许现在可以了。
  • @Anthony - 我添加了有关所需结果(和差异)的信息
  • Transliteration in ruby 的可能重复项

标签: ruby


【解决方案1】:

如果您知道会发生什么,那么您可以在哈希中指定替换:

z = "Håkan"
p z.encode('windows-1250', 'utf-8', fallback: {"å"=>"a"}) # => Hakan

【讨论】:

  • 不幸的是,它取决于输入和目标编码,因此它不是可接受的解决方案:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-03
  • 1970-01-01
相关资源
最近更新 更多