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

后端 未结 4 1244
囚心锁ツ
囚心锁ツ 2020-11-28 08:54

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

# Encoding: utf-8

Is this a preprocessing directive? Are there other uses o

4条回答
  •  北海茫月
    2020-11-28 09:19

    For some reason people refer to this line as 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.

    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.

提交回复
热议问题