How does the magic comment ( # Encoding: utf-8 ) in ruby​​ work?

ghz 1years ago ⋅ 3225 views

Question

How does the magic comment in ruby​​ works? I am talking about:

# Encoding: utf-8

Is this a preprocessing directive? Are there other uses of this type of construction?


Answer

Ruby interpreter instructions at the top of the source file - this is called magic comment. Before processing your source code interpreter reads this line and sets proper encoding. It's quite common for interpreted languages I believe. At least Python uses the same approach.

You can specify encoding in a number of different ways (some of them are recognized by editors):

# encoding: UTF-8
# coding: UTF-8
# -*- coding: UTF-8 -*-

You can read some interesting stuff about source encoding in [this article](http://graysoftinc.com/character-encodings/ruby-19s-three-default- encodings).

The only thing I'm aware of that has similar construction is shebang, but it is related to Unix shells in general and is not Ruby-specific.

magic_comments defined in ruby/ruby