Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save an object to a file?

I would like to save an object to a file, and then read it from the file easily. As a simple example, lets say I have the following 3d array:

m = [[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]],
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]]

Is there an easy Ruby API that I can use to achieve this without programming a parser to interpret the data from the file? In the example I give it is easy, but as the objects become more complicated, it gets annoying to make objects persistent.

like image 861
Flethuseo Avatar asked Sep 09 '25 16:09

Flethuseo


2 Answers

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 it
File.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.

like image 59
Swanand Avatar answered Sep 14 '25 19:09

Swanand


See Marshal: http://ruby-doc.org/core/classes/Marshal.html

-or-

YAML: http://www.ruby-doc.org/core/classes/YAML.html

like image 29
Cory Avatar answered Sep 14 '25 17:09

Cory



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!