EncodingError
RubyERRORNotableEncoding
String encoding problem
Quick Answer
Explicitly set input encoding when reading external data and use encode with the replace or scrub option to handle invalid bytes.
What this means
The base class for all encoding-related errors in Ruby. Subclasses cover invalid byte sequences, missing converters, and incompatible encodings. Encoding errors are common when mixing external data sources with internal string handling.
Why it happens
- 1Reading a binary or Latin-1 file without specifying the encoding
- 2Mixing UTF-8 and ASCII-incompatible byte sequences
Fix
Specify encoding when reading files
Specify encoding when reading files
content = File.read('data.txt', encoding: 'UTF-8')
# or force encoding
content = File.binread('data.bin').force_encoding('UTF-8')
.encode('UTF-8', invalid: :replace, undef: :replace)Why this works
Setting the encoding explicitly lets Ruby validate or replace invalid bytes rather than raising.
Code examples
Invalid byte sequenceruby
"ÿ".encode('UTF-8')
# Encoding::InvalidByteSequenceErrorScrub invalid bytesruby
clean = raw_string.encode('UTF-8', invalid: :replace, undef: :replace, replace: '')Rescue EncodingError broadlyruby
begin
process(str)
rescue EncodingError => e
puts "Encoding issue: #{e.message}"
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