35

We all know the "magical"

# encoding: utf-8

line. But I've seen several other alternative notations, some of them pretty wild. Do you know or use any of those? Is there some more general rule of what is acceptable?

Edit: Ok, apparently there are exactly 3 ways:

# encoding: UTF-8

# coding: UTF-8

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

(more at http://blog.grayproductions.net/articles/ruby_19s_three_default_encodings)

PJK
  • 2,082
  • 3
  • 17
  • 28

1 Answers1

108

No, there are not "exactly 3 ways" to specify the 'magic comment' -- there are an infinite number of them. Any comment on the first line that contains coding: will work, according to JEG2:

... the preferred way to set your source Encoding ... it's called a magic comment. If the first line of your code is a comment that includes the word coding, followed by a colon and space, and then an Encoding name, the source Encoding for that file is changed to the indicated Encoding.

So, any of these should work:

# coding: UTF-8
# encoding: UTF-8
# zencoding: UTF-8
# vocoding: UTF-8
# fun coding: UTF-8
# decoding: UTF-8
# 863280148705622662 coding: UTF-8 0072364213
# It was the night before Christmas and all through the house, not a creature was coding: UTF-8, not even with a mouse.
David J.
  • 31,569
  • 22
  • 122
  • 174
  • Thank you for citing you answer, and clarifying the magic comment stuff for me. Also, just fyi: I tried the JEG2 link but it was down at or around the time of this comment. Cheers! – mkelley33 Apr 13 '13 at 03:44
  • 2
    @mkelley33 Hopefully the link works again soon. For now: http://web.archive.org/web/20120905065913/http://blog.grayproductions.net/articles/ruby_19s_three_default_encodings – David J. Apr 13 '13 at 12:31
  • @DavidJames thank you so much! What a great article. I let JEG know about the site being down. He's such a great host on the ruby rogues podcast. I can't believe I've never visited his blog before, though to be fair I've been doing ruby for just under a year now :) – mkelley33 Apr 13 '13 at 21:13