This becomes even more powerful when you use the
Array.pack and
String.unpack methods.
These let you turn any kind of numeric data into String form for saving, and back again - in this case the term "String" is used in its most general sense; a sequence of bytes, not necessarily interpreted as being characters.
For example...
Code: Select all
byte_string = [0.123, 0.543, 1.462, 7.890].pack('F*')
...gives you a String byte-sequence that encodes the array of float numbers (single precision in this case).
And...
Code: Select all
my_array = byte_string.unpack('F*')
...will get you back to the original array.
Also, check out the
Marshal class - even more powerful!
This has methods that allow you to turn almost any Ruby object into a serialized String and back again - including even Arrays etc. nested many levels deep.
Code: Select all
hashed_arrays = { "Array1" => [10,20,30], "Array2" => [40,50,60] }
File.open(my_file,"w"){|file| Marshal.dump(hashed_arrays, file)}
hashed_arrays = File.open(my_file, "r"){|file| Marshal.load(file)}
You can even make this work for your own custom classes of object if you define the correct 'load' and 'dump' methods in your new class - all you need is some way to turn your object into a string and back again (possibly by the Marshal methods of any component objects).
There are a few exceptions where this doesn't work - for example many of the FS GUI objects lack the necessary Marshal methods, so, as yet, you can't easily save GraphicsPaths, Pens, etc.