Encoding::ConversionError
RubyERRORCommonEncoding

String encoding conversion failed

Quick Answer

Use String#encode with :invalid => :replace and :undef => :replace to safely convert strings, replacing unconvertible characters.

What this means

Raised when converting a string from one encoding to another encounters a character that cannot be represented in the target encoding, or an invalid byte sequence in the source string.

Why it happens
  1. 1Converting a UTF-8 string with emoji to ISO-8859-1 (which cannot represent them)
  2. 2Source string contains invalid byte sequences for its declared encoding
  3. 3Concatenating strings with incompatible encodings

Fix 1

Use encode with replacement options

Use encode with replacement options
# Safe conversion — replace unconvertible chars with ?
result = str.encode('ISO-8859-1',
  invalid: :replace,
  undef:   :replace,
  replace: '?')

Why this works

:invalid replaces invalid byte sequences; :undef replaces characters with no mapping in the target encoding.

Fix 2

Force UTF-8 and scrub invalid bytes

Force UTF-8 and scrub invalid bytes
# Scrub invalid byte sequences from external input
clean = str.encode('UTF-8', 'binary',
  invalid: :replace,
  undef:   :replace).scrub

Why this works

Treating the source as binary and converting to UTF-8 with replacement handles arbitrary byte sequences from external sources.

Code examples
Triggerruby
"hello 😀".encode('ISO-8859-1')
# Encoding::UndefinedConversionError: U+1F600 from UTF-8 to ISO-8859-1
Check encodingruby
str.encoding          # => #<Encoding:UTF-8>
str.valid_encoding?   # => true/false
Sources
Official documentation ↗

Ruby Core Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Ruby errors