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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)