Encoding::CompatibilityError
RubyERRORNotableEncoding
Encodings are incompatible for concatenation
Quick Answer
Normalise all strings to the same encoding (usually UTF-8) before combining them.
What this means
Raised when two strings with incompatible encodings are used together in an operation such as concatenation or comparison. For example, concatenating a UTF-8 string with a UTF-16 string.
Why it happens
- 1Concatenating strings with different incompatible encodings
- 2Interpolating a binary-encoded string into a UTF-8 string
Fix
Normalise to UTF-8 before combining
Normalise to UTF-8 before combining
a = "UTF-8 string"
b = "binary data".force_encoding('BINARY')
combined = a + b.encode('UTF-8', invalid: :replace, undef: :replace)Why this works
Encoding both strings to UTF-8 makes them compatible for concatenation.
Code examples
Reproducing the errorruby
a = "hello".encode('UTF-8')
b = "world".encode('UTF-16')
a + b
# Encoding::CompatibilityError: incompatible character encodings: UTF-8 and UTF-16Check compatibilityruby
Encoding.compatible?(a, b) # => nil if incompatible
Normalise before concatruby
combined = a + b.encode(a.encoding)
Same 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