Read more

Ruby's default encodings can be unexpected

Tobias Kraze
July 12, 2016Software engineer at makandra GmbH

Note: This applies to plain Ruby scripts, Rails does not have this issue.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

When you work with Ruby strings, those strings will get some default encoding, depending on how they are created. Most strings get the encoding Encoding.default_internal or UTF-8, if no encoding is set. This is the default and just fine.

However, some strings will instead get Encoding.default_external, notably

  • the string inside a StringIO.new
  • some strings created via CSV
  • files read from disk
  • strings read from an IRB

Encoding.default_external defaults to whatever locale charmap says on your system. This is usually UTF-8 as well, but can default to something less sane.

If you encounter mysterious encoding errors (like Encoding::CompatibilityError: incompatible character encodings: ISO-8859-1 and UTF-8) this might be what happened.

You can override this behaviour by manually setting Encoding.default_external = 'UTF-8'. You should do this at the very beginning of your code.

Posted by Tobias Kraze to makandra dev (2016-07-12 19:02)