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?
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:
Instead of
ASCII
inencode
you can use alsoEncoding.default_external
: