为什么我得到#inspect的Encoding :: CompatibilityError? [英] Why do I get a Encoding::CompatibilityError with #inspect?

查看:204
本文介绍了为什么我得到#inspect的Encoding :: CompatibilityError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码没有问题:

#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ä,soll das?')我得到一个Encoding :: CompatibilityError: p>

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>'

为什么?

更重要的是,如何避免?

And more important: How can I avoid it?

推荐答案

错误消息解释了为什么:
检查结果必须是ASCII,或使用默认的外部编码

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

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

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?>

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

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

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

这篇关于为什么我得到#inspect的Encoding :: CompatibilityError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆