I have a 2D array containing many instances of a class. The class contains 4 arrays. I would like to save and load the 2D array to/from disk using Marshal. I have successfully used Marshal for this purpose with other 2D arrays containing classes, but those classes did not contain an array. Here is the definition of the class giving me trouble.
class Light
attr_accessor :R,:G,:B,:A
def initialize(i)
@R = Array.new(4, i)
@G = Array.new(4, i)
@B = Array.new(4, i)
@A = Array.new(4, i)
end
@R
@G
@B
@A
end
I have tried defining my own marshal functions in the Light class:
def marshal_dump
{'R' => @R,'G' => @G,'B' => @B,'A' => @A}
end
def marshal_load(data)
self.R = data['R']
self.G = data['G']
self.B = data['B']
self.A = data['A']
end
Here is the creation of the 2D array containing this class
def createLightMap(width,height)
a = Array.new(width) { Light.new(0.7) }
a.map! { Array.new(height) { Light.new(0.7) } }
return a
end
@lightMap = createLightMap(10,10)
Here is how I save and load
#save
File.open('lightData','w') do |file|
Marshal.dump(@lightMap, file)
end
#load
@lightMap = if File.exists?('lightData')
File.open('lightData','w') do |file|
Marshal.load(file)
end
else
puts 'no light data found'
end
Upon load, I receive the error “in ‘load’: dump format error (unlinked, index: -96) (Argument Error)”
I have tried with and without custom dump/load marshal functions. I am using jruby 1.5.1, ruby 1.8.7
I don’t think it’s the Marshal dump/load that is the problem, it’s probably just the file I/O. This works fine for me (without custom marshaling):