Ruby writing and reading an object to a file

So, my goal is to easily save some data to disk for later use. How do you just write and then read the object? Therefore, 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 create obj from this very fast

 obj = C.new("foo", "bar") #just gave it some random values 

Then I can turn this into a kind of id

 string = obj.to_s #which returns "<C:0x240dcf8 @a="foo", @b="bar">" 

I can finally print this line in a file or something like that. My question is: how do I again include this identifier back in the object? I know that I can independently parse this information and perform the initialization function, which accepts this information, but, of course, the ruby ​​has something built-in to turn it back into an object, right?

+4
source share
2 answers

Ruby has several 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 
+5
source

This string cannot be returned to the object, essentially just a hash.

Are you 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 you to store them outside the current active script. This data can subsequently be read, and the original objects restored.

There are always security issues, make sure you know what you're reading.

Also note that some types of objects cannot be marshaled, things that are related to IO, etc.

EDIT: Also, yaml, as Kyle points out, is a good user-friendly form of string representation that should also be mentioned

+2
source

Source: https://habr.com/ru/post/1469064/


All Articles