Featured image

If you work with text often especially when parsing scraped or external data you’ve almost certainly run into encoding issues. Typically, it goes like this: you receive text from a parser in binary encoding (ASCII-8BIT), and you need to convert it to UTF-8 for further processing.

In Ruby, you’d normally just call the String#encode method. However, if the text contains malformed characters, you’ll hit an exception like 'String#encode': "\xEF" from ASCII-8BIT to UTF-8 (Encoding::UndefinedConversionError). To strip out the bytes that can’t be transcoded, call encode with the replace: '' option (see the example in the screenshot).

Alternatively, you can use String#force_encoding, which leaves the underlying bytes untouched and simply changes the string’s encoding label, and then call String#scrub to replace any invalid byte sequences.

Have you dealt with text processing in Ruby? What encoding headaches have you run into?

Encoding::BINARY.name  # ASCII-8BIT
Encoding::BINARY.names # ["ASCII-8BIT", "BINARY"]
Encoding.list          # [#<Encoding:BINARY (ASCII-8BIT)>, #<Encoding:UTF-8>, ..]
Encoding.find('utf-8') # #<Encoding:UTF-8>

t = "\xEF\x73\x6F\x6D\x65\x20\x74\x65\x78\x74".b
t.encode('UTF-8', invalid: :replace, undef: :replace) # "�some text"
t.encode('UTF-8', replace: '')                        # "some text"

s = "\xEF\x6F\x74\x68\x65\x72\x20\x73\x74\x72\x69\x6E\x67\x20\xEE".b
s.force_encoding('UTF-8')
s.scrub                                               # "�other string�"
s.scrub('')                                           # "other string"