2.0.0 Upgrade Notes (Draft)¶
A script encoding is now UTF-8 by default¶
The default script encoding was changed from US-ASCII to UTF-8.
Pros¶
- You can write UTF-8 string literal with no magic comment.
Cons¶
- A string literal that contains such as "\xff", called "binary string literal", now yields (invalid) UTF-8 string object rather than ASCII-8BIT one.
Typical case¶
For example, when you attempt to concatenate a ASCII-8BIT string (e.g, the result of File.binread) and a binary string literal, you may encounter an exception:
p File.binread("binfile") + "\xff" #=> 1.9: "\xFF\xFF" #=> 2.0: incompatible character encodings: ASCII-8BIT and UTF-8 (Encoding::CompatibilityError)
When to encounter the problem¶
You may encounter such an exception when you are loading a script that satisfies the following two conditions:
- it omits a magic comment, and - it uses a binary string literal.
Note that you will not always see the exception; if an either string is compatible to US-ASCII (i.e., contains only ASCII code 0--127), it will be implicitly converted to the same encoding as the other string.If you are using a third-parties' libraries (gem) that satisfy the two conditions, you need to ask the author to fix and update it.
How to fix¶
As a workaround that makes it 1.9-compatible, please set the encoding to US-ASCII by explicitly add a magic comment to the script in question.
# coding: US-ASCII
If you want to use both non-US-ASCII string literal and binary one at a time, please use String#b method for the latter.
"\xff\xff".b #=> "\xFF\xFF"
Note that a magic comment is also mandatory when you use non-US-ASCII string literal (as 1.9 does).
スクリプトエンコーディングがデフォルトで UTF-8 に¶
デフォルトのスクリプトエンコーディングが US-ASCII から UTF-8 に変更されました。
メリット¶
- マジックコメント無しで UTF-8 文字列リテラルが使えます。
デメリット¶
- "\xff" などを含む文字列リテラル (バイナリ文字列リテラルと呼びます) が、ASCII-8BIT ではなく、(不正な) UTF-8 文字列オブジェクトを生成します。
典型的な問題¶
例えば、ASCII-8BIT 文字列 (File.binread の返り値など) とバイナリ文字列リテラルを結合しようとすると、例外が発生します。
p File.binread("binfile") + "\xff" #=> 1.9: "\xFF\xFF" #=> 2.0: incompatible character encodings: ASCII-8BIT and UTF-8 (Encoding::CompatibilityError)
発生条件¶
以下の 2 条件を満たすスクリプトをロードすると、例外が発生することがあります。
- マジックコメントを省略している - バイナリ文字列を使用している
常に例外が起きるわけではないことに注意してください。いずれかの文字列が US-ASCII 互換な場合 (ASCII コードで 0 から 127 の文字しか含んでいない場合) 、もう片方の文字列のエンコーディングに自動的に変換されます。この 2 条件を満たすサードパーティのライブラリ (gem) を使用している場合は、その作者に連絡して修正してもらう必要があります。
修正方法¶
差し当たり 1.9 互換にするには、問題のスクリプトにマジックコメントを追加して US-ASCII を明示してください。
# coding: US-ASCII
非 US-ASCII 文字列リテラルとバイナリ文字列リテラルを同時に扱いたい場合は、バイナリ文字列リテラルに対して String#b メソッドを使用してください。
"\xff\xff".b #=> "\xFF\xFF"
非 US-ASCII 文字列リテラルを使用する場合は、マジックコメントが必須であることに注意してください (1.9 と同様) 。