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

后端 未结 1 628
时光取名叫无心
时光取名叫无心 2021-01-22 05:22

The following code works without problem:

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


        
1条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-22 06:29

    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
        ("" % @txt).encode('ASCII', :undef => :replace, :invalid => :replace)
      end
    end
    
    p Text.new('Hä, was soll das?') #-> 
    

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

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

    0 讨论(0)
提交回复
热议问题