How can I save an object to a file? How can I save an object to a file? ruby ruby

How can I save an object to a file?


You need to serialize the objects before you could save them to a file and deserialize them to retrieve them back. As mentioned by Cory, 2 standard serialization libraries are widely used, Marshal and YAML.

Both Marshal and YAML use the methods dump and load for serializing and deserializing respectively.

Here is how you could use them:

m = [     [      [0, 0, 0],      [0, 0, 0],      [0, 0, 0]     ],     [      [0, 0, 0],      [0, 0, 0],      [0, 0, 0]     ]    ]# Quick way of opening the file, writing it and closing itFile.open('/path/to/yaml.dump', 'w') { |f| f.write(YAML.dump(m)) }File.open('/path/to/marshal.dump', 'wb') { |f| f.write(Marshal.dump(m)) }# Now to read from file and de-serialize it:YAML.load(File.read('/path/to/yaml.dump'))Marshal.load(File.read('/path/to/marshal.dump'))

You need to be careful about the file size and other quirks associated with File reading / writing.

More info, can of course be found in the API documentation.


YAML and Marshal are the most obvious answers, but depending on what you're planning to do with the data, sqlite3 may be a useful option too.

require 'sqlite3'm = [[[0, 0, 0], [0, 0, 0], [0, 0, 0]],[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]db=SQLite3::Database.new("demo.out")db.execute("create table data (x,y,z,value)")inserter=db.prepare("insert into data (x,y,z,value) values (?,?,?,?)")m.each_with_index do |twod,z|  twod.each_with_index do |row,y|    row.each_with_index do |val,x|      inserter.execute(x,y,z,val)    end  endend