Ruby 2.0中的二进制字符串文字 [英] Binary string literals in Ruby 2.0

查看:112
本文介绍了Ruby 2.0中的二进制字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当升级到Ruby 2.0时,测试用例开始失败:

When upgrading to Ruby 2.0, a test case started to fail:

expected = "\xD1\x9B\x86"
assert_equal expected, actual

包含以下消息:

<"ћ\x86"> expected but was
<"\xD1\x9B\x86">.

实际变量包含获取的二进制字符串从外部库调用。

The actual variable contains a binary string obtained from an external library call.

问题是源文件(因此字符串文字)的默认编码从US-ASCII更改为UTF-8。

The problem is that the default encoding of source files (and therefore string literals) changed in Ruby 2.0 from US-ASCII to UTF-8.

推荐答案

解决方案是更改字符串文字的定义,以强制执行其编码。有几个可能的选择:

The solution is to change the definition of the string literal to enforce its encoding. There are a few possible options to do this:

使用数组#包(所有版本的Ruby):

Use Array#pack (all versions of Ruby):

expected = ["d19b86"].pack('H*')

使用 String#b (仅限于Ruby> = 2.0):

Use String#b (Ruby >= 2.0 only):

expected = "\xD1\x9B\x86".b

使用String#force_encoding (仅限于Ruby> = 1.9):

Use String#force_encoding (Ruby >= 1.9 only):

expected = "\xD1\x9B\x86".force_encoding("ASCII-8BIT")

这篇关于Ruby 2.0中的二进制字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆