5

Ruby says that Encoding::BINARY and Encoding::ASCII-8BIT are the same.

Encoding::BINARY == Encoding::ASCII_8BIT
#=> true

We explicitly create a binary string and ruby still says it's ASCII_8BIT.

String.new("ABC", encoding: Encoding::BINARY).encoding
#=> #<Encoding:ASCII-8BIT>

Likewise, force_encoding cannot create a BINARY, it just creates an ASCII-8BIT string.

It seems that BINARY is simply an alias for ASCII-8BIT. Are there any differences?

1 Answer 1

6

Your observation is correct: BINARY and ASCII-8BIT are indeed aliases and being an alias implies there are no differences as it's just another name for the same encoding, method, etc.

Looking at the source code is the most reliable way to confirm this. CRuby's character encodings can be found in the enc directory. The ASCII-8BIT encoding is defined in the ascii.c file containing the following line (in 2.5.0, it's line 61):

ENC_ALIAS("BINARY", "ASCII-8BIT")

ENC_ALIAS works like Ruby's alias keyword (alias, original name).

Confirming that BINARY or another encoding name is an alias can be done in pure Ruby too. One possibility is calling the Encoding.aliases method which returns a hash (alias => original):

Encoding.aliases['BINARY']  # => "ASCII-8BIT"

Other useful methods are Encoding#name which returns the original name and Encoding#names which also returns all aliases:

Encoding::BINARY.names    # => ["ASCII-8BIT", "BINARY"]
Encoding::US_ASCII.names  # => ["US-ASCII", "ASCII", "ANSI_X3.4-1968", "646"]

Or a way without any Encoding methods:

Encoding::BINARY.equal?(Encoding::ASCII_8BIT)

As the == method is often overwritten and may return true even if both operands are two different objects, BasicObject#equal? should be called to check if they are the same object. E.g. 1 and 1.0 have the same value (== returns true) but not the same object identity (equal? returns false).

Sign up to request clarification or add additional context in comments.

3 Comments

I was trying to find where those constants were defined, but I was expecting them to show up in the ruby "stubs" that come with my IDE, and I didn't think to look in the C source. Thanks!
May I edit the answer to start with “No” rather than “Yes” as the question is “Are there any differences?” and the answer is “there are no differences”?
@MartinDorey: I've rephrased it but if you still want to improve the beginning or any other part of the answer feel free to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.