arrow_backward Back to blog

Ruby 1.9 Encodings

When i came to Ruby 1.9, the first problem i met is the encodings. Gregory Brown said, in a training session at the Lone Start Rubyconf, “Ruby 1.8 works in bytes. Ruby 1.9 works in characters.” In Ruby 1.8, you have to deal with those bytes and it does not provide any functions with encodings. But in Ruby 1.9, i think you must know about the encoding stuff to make you life easier. Let us talk about the fouce Encodings in Ruby 1.9 by examples.

The Source File Encoding

The source file encoding is the character encoding of a given source file. It is US-ASCII by default. When you create a String literal in your code, it is assigned the Encoding of your source. So you have to changing the source Encoding when you want to place any non-ASCII content in a String literal.

As you can see in the no_encoding.rb, the error came out as “invalid multibyte char (US-ASCII)” when there is an chinese string in the source file. That is because when nothing of encoding is specified, Ruby will default to ASCII. But after the encoding is specified by adding the encoding comment, it works.

The String Encoding

Each string has its own own encoding, which you can access with String#encoding method:

But the transcoding will fail if the encoding does not support all characters in your string:

The External Encoding

The encoding of the data in an IO stream is known by Ruby as the object’s external encoding.The default external Encoding is pulled from your environment.

Here is how the exernal encoding works:

if the file is not going to use the default extrenal encoding, you can override it:

The Internal Encoding

The encoding that the programmer wishes to use with the data in a stream is the internal encoding. The default internal encoding is nil unless set explicitly.

We could specify our internal encoding when opening the file if the external encoding won’t match the encoding we want to use internally.


New Project Request