Keith Bennett
Keith Bennett

Reputation: 4970

Ruby not respecting # encoding specification

Given the following script (it must be in its own file):

#!/usr/bin/env ruby

# encoding: binary

s = "\xe1\xe7\xe6\x07\x00\x01\x00"
puts s.encoding

The output of this is "UTF-8". Why isn't it binary (ASCII-8BIT)?

Upvotes: 1

Views: 36

Answers (1)

Keith Bennett
Keith Bennett

Reputation: 4970

Because the # encoding: binary must be on the line immediately following the #!/usr/bin/env ruby. Alternatively, if there is no #!/usr/bin/env ruby line, it must then be on the first line of the file.

When the blank line is removed (i.e. the encoding specification is on the second line):

#!/usr/bin/env ruby
# encoding: binary

s = "\xe1\xe7\xe6\x07\x00\x01\x00"
puts s.encoding

...the output is "ASCII-8BIT".

Here is a link to the Ruby documentation regarding magic comments such as encoding (thanks to Stefan who mentioned this in a comment):

https://ruby-doc.org/core-3.1.2/doc/syntax/comments_rdoc.html#label-Magic+Comments

Upvotes: 2

Related Questions