Home > Software engineering >  How to save an array of objects into a file in ruby?
How to save an array of objects into a file in ruby?

Time:11-04

I have an array of objects, where the objects are instances of a class. I would like to save this array into a file in such format that I could read the file back to an array and the objects and its' instance variable values would be as they were before saving. Does someone know how this could be achieved?

The class instance objects that I would like to save to a file are fairly complex containing tens of instance variables that are often other class instance variables themselves.

WHAT I HAVE TRIED:

According to this post I tried the following:

TRIAL1:

Save file:

require 'pp'
$stdout = File.open('path/to/file.txt', 'w')
pp myArray

Load file:

require 'rubygems'
require 'json'
buffer = File.open('path/to/file.txt', 'r').read
myArray = JSON.parse(buffer)

but I got a JSON::ParserError

TRIAL2:

Save file

serialized_array = Marshal.dump(myArray)
File.open('./myArray.txt', 'w') {|f| f.write(serialized_array) }

received Encoding::UndefinedConversionError

CodePudding user response:

TRIAL1 doesn't work because pp "prints arguments in pretty form" and that's not necessarily JSON.

TRIAL2 probably isn't working because Marshal produces binary data (not text) and you're not working with your file in binary mode, that could lead to encoding and EOL problems. Besides, Marshal isn't a great format for persistence since the format is tied to the version of Ruby you're using.

A modification of TRIAL1 to write JSON is probably the best solution these days:

require 'json'
File.open('path/to/file.json', 'w') { |f| JSON.dump(myArray, f) }

CodePudding user response:

Finally managed to find a solution that worked!

dump = Marshal.dump(myArray)
File.write('./myarray', myArray, mode: 'r b')
dump = File.read('./myarray')
user = Marshal.restore(dump)

Marshall was able to do the trick after changing the encoding to binary mode

  • Related