假设我有类Line的对象行:
class Line def initialize point1,point2 @p1 = point1 @p2 = point2 end end
line = Line.new …
如何对行对象进行二进制序列化?我尝试过:
data = Marshal::dump(line,"path/to/still/unexisting/file")
解决方法
喜欢这个:
class Line attr_reader :p1,:p2 def initialize point1,point2 @p1 = point1 @p2 = point2 end end line = Line.new([1,2],[3,4])
保存线:
FNAME = 'my_file' File.open(FNAME,'wb') {|f| f.write(Marshal.dump(line))}
检索到line1:
line1 = Marshal.load(File.binread(FNAME))
确认它有效:
line1.p1 # => [1,2]