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

后端 未结 4 1243
囚心锁ツ
囚心锁ツ 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:01

    This magic comment tells Ruby the source encoding of the currently parsed file. As Ruby 1.9.x by default assumes US_ASCII you have tell the interpreter what encoding your source code is in if you use non-ASCII characters (like umlauts or accented characters).

    The comment has to be the first line of the file (or below the shebang if used) to be recognized.

    There are other encoding settings. See this question for more information.

    Since version 2.0, Ruby assumes UTF-8 encoding of the source file by default. As such, this magic encoding comment has become a rarer sight in the wild if you write your source code in UTF-8 anyway.

提交回复
热议问题