Why do I get a Encoding::CompatibilityError with #

2019-02-27 13: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条回答
Viruses.
2楼-- · 2019-02-27 14:05

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)
查看更多
登录 后发表回答