为什么我用#inspect获得Encoding :: CompatibilityError?

时间:2015-08-25 19:59:05

标签: ruby encoding inspect

以下代码可以正常运行:

#encoding: utf-8
class Text
  def initialize(txt)
    @txt = txt
  end
  def inspect
    "<Text: %s>" % @txt
  end
end

p Text.new('Hello World')

但是,如果我尝试p Text.new('Hä, was soll das?'),我会得到一个Encoding :: CompatibilityError:

inspect_with_umlaut.rb:26:in `p': inspected result must be ASCII only or use the default external encoding (Encoding::CompatibilityError)
  from inspect_with_umlaut.rb:26:in `<main>'

为什么这样?

更重要的是:我该如何避免它?

1 个答案:

答案 0 :(得分:3)

错误消息已解释原因: 检查结果必须仅为ASCII或使用默认外部编码

在这种情况下,inspect-command获取UTF-8字符(非ASCII),但默认编码似乎是另一种。 可以在Encoding.default_external中读取默认编码。

为避免错误,您必须对inspect的结果进行编码:

#encoding: utf-8
class Text
  def initialize(txt)
    @txt = txt
  end
  def inspect
    #force ASCII and replace invalid/undefined characters
    ("<Text: %s>" % @txt).encode('ASCII', :undef => :replace, :invalid => :replace)
  end
end

p Text.new('Hä, was soll das?') #-> <Text: H?, was soll das?>

而不是ASCII encode,您也可以使用Encoding.default_external

("<Text: %s>" % @txt).encode(Encoding.default_external, :undef => :replace)