How to Write to File When Using Marshal::Dump in Ruby for Object Serialization

How to write to file when using Marshal::dump in Ruby for object serialization

Like this:

class Line
attr_reader :p1, :p2
def initialize point1, point2
@p1 = point1
@p2 = point2
end
end

line = Line.new([1,2], [3,4])

Save line:

FNAME = 'my_file'

File.open(FNAME, 'wb') {|f| f.write(Marshal.dump(line))}

Retrieve into line1:

line1 = Marshal.load(File.binread(FNAME))

Confirm it works:

line1.p1 # => [1, 2]

How can I save an object to a file?

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

-or-

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

How does ruby serialization (Marshaling) work?

The Ruby marshalling methods store the type of the object they're encoding. The way those two hooks work is like this:

  • marshal_dump has to return some data describing the state of your object. Ruby couldn't care less about the format of this data — it just has to be something that your marshal_load method can use to reconstruct the object's state.

  • marshal_load is called on the marshalled object just after it's been recreated. It's basically the initialize method for a marshalled object. It's passed whatever object marshal_dump returned and has to use that data to reconstruct its state.

Here's an example:

class Messenger

attr_accessor :name, :message

def marshal_dump
{'name' => name, 'message' => message}
end

def marshal_load(data)
self.name = data['name']
self.message = data['message']
end

end

How to read a large file into a string

Marshal is a binary format, so you need to read and write in binary mode. The easiest way is to use IO.binread/write.

...
IO.binwrite('mat_save', mat_dump)
...
mat_dump = IO.binread('mat_save')
@mat = Marshal.load(mat_dump)

Remember that Marshaling is Ruby version dependent. It's only compatible under specific circumstances with other Ruby versions. So keep that in mind:

In normal use, marshaling can only load data written with the same major version number and an equal or lower minor version number.

Get the size in KB of Marshal.dump output

Since the output of Marshal.dump is a string, you can just ask for the length of that. The safest way to do this is to ask for bytesize:

dumped = Marshal.dump(array)
kb = dumped.bytesize / 1024

The bytesize method always returns the length of a string in bytes, whereas length returns the length of the string in characters. The two values can differ if you use a multi-byte encoding method like UTF-8.

marshal dump format error(0xa)

You are reading the file in binary mode but the contents haven't been dumped like that.

use:

$settings = Marshal.load(File.open(file_path))



Related Topics



Leave a reply



Submit