Why do I get a Encoding::CompatibilityError with #inspect?

风流意气都作罢 提交于 2019-12-02 05:15:35

问题


The following code works without problem:

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

p Text.new('Hello World')

But if I try p Text.new('Hä, was soll das?') I get a 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>'

Why this?

And more important: How can I avoid it?


回答1:


The error message explains already the why: inspected result must be ASCII only or use the default external encoding

In this case the inspect-command gets a UTF-8 character (Not ASCII), but the default encoding seems to be another. The default encoding can be read in Encoding.default_external.

To avoid the error you must encode the result of 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?>

Instead of ASCII in encode you can use also Encoding.default_external:

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


来源:https://stackoverflow.com/questions/32212974/why-do-i-get-a-encodingcompatibilityerror-with-inspect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!