Is there a simple way to write binary data into binary file like we used to do in C/C++? For example, how can I create a 4-byte file with serialized 4-byte integer value without using fancy math?
5 Answers
You can use Array#pack and String#unpack to convert to and from binary representations. Combine them with IO#write and IO#read, and away you go.
2 Comments
String#unpack ?I recently had a similar problem for work. I used the BinData gem and it worked a treat. You just do something like:
File.open('test.bin', 'wb') {|file| BinData::Int32be.new(12345).write(file) }
and you don't need to remember any Array#pack codes.
2 Comments
There is File#binwrite to write binary data:
File.binwrite("test.bin", my_binary_data)
1 Comment
File.open doThere are Marshal.dump and Marshal.load methods you can use.
Here's a link: http://en.wikipedia.org/wiki/Serialization#Ruby.
And another that saves the data to a file: http://rubylearning.com/satishtalim/object_serialization.html.
2 Comments
In my humble oppinion, ruby wasn't made for such tasks. If you have to write to binary files a lot, it would be easiest to write some c functions for that and call them from ruby, which is quite easy using swig. I'm doing the same thing at the moment to write a raid simulator.