How can I avoid putting the magic encoding comment on top of every UTF-8 file in Ruby 1.9? How can I avoid putting the magic encoding comment on top of every UTF-8 file in Ruby 1.9? ruby ruby

How can I avoid putting the magic encoding comment on top of every UTF-8 file in Ruby 1.9?


I think you can either

  1. use -E utf-8 command line argument to ruby, or
  2. set your RUBYOPT environment variable to "-E utf-8"


In my opinion, explicit is not always better than implicit.

When almost all the source you use is UTF-8 compatible, you can easily avoid putting the magic encoding comment by using Ruby's -Ku command-line options.

Don't confuse the "u" parameter of the -K options with -U options.

-Ku : set internal and script encoding to utf-8-U  : set internal encoding to utf-8

Then, set the magic encoding comment only in scripts that need it. Remember, convention over configuration!

You can set the environment variable RUBYOPT=-Ku

See Ruby's command-line options at http://www.manpagez.com/man/1/ruby/.


Explicit is better than implicit. Writing out the name of the encoding is good for your text editor, your interpreter, and anyone else who wants to look at the file. Different platforms have different defaults -- UTF-8, Windows-1252, Windows-1251, etc. -- and you will either hamper portability or platform integration if you automatically pick one over the other. Requiring more explicit encodings is a Good Thing.

It might be a good idea to integrate your Rails app with GetText. Then all of your UTF-8 strings will be isolated to a small number of translation files, and your Ruby modules will be clean ASCII.