Leo's Technical Blog

Reading a Binary File on Ruby

Introduction

user

Leo Soto


tips, ruby, windows

Reading a Binary File on Ruby

Posted by Leo Soto on .
Featured

tips, ruby, windows

Reading a Binary File on Ruby

Posted by Leo Soto on .

No, it is not as simple as:

contents = IO.read(path_to_binary_file)  

Because it does not work well on Windows platforms. In code meant to be compatible with Ruby 1.8 you should do:

contents = open(path_to_binary_file, "rb") {|io| io.read }  

Obviously, the key is the binary flag. It can not be passed to IO.read.

And if you are using Ruby 1.9.2 or any more recent version (and you should!), IO.binread is a simpler option:

contents = IO.binread(path_to_binary_file)  

I learned this because a co-worker had a mysterious problem sending email attachments with rails. I was not able to help her (that IO.read never seemed suspicious to me), but once she found the solution, all became clear.

But you know, the real bug was she using Windows as a development platform, right?.

Update: Changed recipe to use open instead of IO.open. Thanks to Brian Hartin for pointing that in the comments (comment lost in a blog platform change, unfortunately)

Update: Show IO.binread as an option for Ruby 1.9.2+. Thanks for Gee Bee for suggesting that in the comments.