使用 Ruby 自动打开二进制文件 [英] Automatically open a file as binary with Ruby

查看:22
本文介绍了使用 Ruby 自动打开二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Ruby 1.9 打开多个文件并将它们复制到存档中.现在有一些二进制文件,但有些没有.由于 Ruby 1.9 不会自动打开二进制文件作为二进制文件,有没有办法自动打开它们?(所以.class"是二进制的,.txt"不是)

I'm using Ruby 1.9 to open several files and copy them into an archive. Now there are some binary files, but some are not. Since Ruby 1.9 does not open binary files automatically as binaries, is there a way to open them automatically anyway? (So ".class" would be binary, ".txt" not)

推荐答案

其实,Alex D 之前的回答是不完整的.虽然在 Unix 文件系统中确实没有文本"模式,但 Ruby 确实在以二进制和非二进制模式打开文件之间有所不同:

Actually, the previous answer by Alex D is incomplete. While it's true that there is no "text" mode in Unix file systems, Ruby does make a difference between opening files in binary and non-binary mode:

s = File.open('/tmp/test.jpg', 'r') { |io| io.read }
s.encoding
=> #<Encoding:UTF-8>

不同于(注意"rb")

s = File.open('/tmp/test.jpg', 'rb') { |io| io.read }
s.encoding
=> #<Encoding:ASCII-8BIT>

后者,正如 docs 所说,设置外部编码为 ASCII-8BIT,它告诉 Ruby 不要尝试以 UTF-8 解释结果.您可以通过使用 s.force_encoding('ASCII-8BIT') 显式设置编码来实现相同的目的.如果您想将二进制文件读入字符串并移动它们(例如,将它们保存到数据库等),这是关键.

The latter, as the docs say, set the external encoding to ASCII-8BIT which tells Ruby to not attempt to interpret the result at UTF-8. You can achieve the same thing by setting the encoding explicitly with s.force_encoding('ASCII-8BIT'). This is key if you want to read binary into a string and move them around (e.g. saving them to a database, etc.).

这篇关于使用 Ruby 自动打开二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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