Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby writing and reading object to file

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?

like image 216
user2167197 Avatar asked Mar 13 '13 20:03

user2167197


People also ask

Which method is used writing to the file in Ruby?

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.


2 Answers

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
like image 104
Kyle Avatar answered Sep 24 '22 20:09

Kyle


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

like image 24
loosecannon Avatar answered Sep 22 '22 20:09

loosecannon