Ok, so my goal is to easily save some data to disk for later use. How do you simply write and then read an object? So if i have a simple class
class C
attr_accessor :a, :b
def initialize(a, b)
@a, @b = a, b
end
end
So if I make a obj from that really fast
obj = C.new("foo", "bar") #just gave it some random values
Then I can turn that into a kinda id
string = obj.to_s #which returns "<C:0x240dcf8 @a="foo", @b="bar">"
I can finally print this string to a file or something. My question, is how do I then turn this id back into an object again? I know I could pick apart the information myself and make an initialize function that takes in that info, but surely ruby has something built in to turn this back into an object, right?
Writing to the file With the help of syswrite method, you can write content into a file. File needs to be opened in write mode for this method. The new content will over write the old content in an already existing file.
Ruby has a couple of ways to serialize an object:
c = C.new("foo", "bar")
# using YAML
require 'yaml'
yaml_serialized = c.to_yaml
c_object = YAML.load yaml_serialized
# using Marshal
marshal_serialized = Marshal.dump c
c_object = Marshal.load marshal_serialized
That string cant be turned back into an object, its essentially just a hash.
You are looking for Marshalling or serialization of objects.
http://www.ruby-doc.org/core-2.0/Marshal.html
The marshaling library converts collections of Ruby objects into a byte stream, allowing them to be stored outside the currently active script. This data may subsequently be read and the original objects reconstituted.
There are always security concerns when doing that, make sure you know what you are reading in.
Also note some types of objects cannot be marshaled, things that involve IO etc
EDIT: Also, yaml as Kyle points out, is a good human readable form of string representation that should mentioned too
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With