Encoding::UndefinedConversionError
RubyERRORNotableEncoding
Character has no mapping in target encoding
Quick Answer
Use encode with undef: :replace to substitute unmappable characters instead of raising.
What this means
Raised when a character exists in the source string but has no equivalent in the target encoding. Different from InvalidByteSequenceError — the bytes are valid, but the character cannot be represented in the destination encoding.
Why it happens
- 1Converting a UTF-8 string with emoji or non-Latin characters to ISO-8859-1
- 2Encoding to ASCII from a string containing multi-byte characters
Fix
Replace undefined characters on encode
Replace undefined characters on encode
result = text.encode('ISO-8859-1', undef: :replace, replace: '?')Why this works
undef: :replace substitutes any character without a target encoding equivalent with the replacement string.
Code examples
Reproducing the errorruby
"😀".encode('ISO-8859-1')
# Encoding::UndefinedConversionError: U+1F600 from UTF-8 to ISO-8859-1Replace undefinedruby
safe = str.encode('ASCII', undef: :replace, replace: '')Rescue the errorruby
begin
encoded = str.encode('ISO-8859-1')
rescue Encoding::UndefinedConversionError => e
puts "Cannot encode: #{e.error_char}"
endSame error in other languages
Sources
Official documentation ↗
Ruby Core Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev