在Ruby中使用Marshal :: dump进行对象序列化时如何写入文件 [英] How to write to file when using Marshal::dump in Ruby for object serialization
本文介绍了在Ruby中使用Marshal :: dump进行对象序列化时如何写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有 Line 类的对象 line :
class Line
def initialize point1, point2
@p1 = point1
@p2 = point2
end
end
line = Line.new ...
如何对行对象进行二进制序列化?我尝试过:
How can I binary serialize the line object? I tried with:
data = Marshal::dump(line, "path/to/still/unexisting/file")
但是它创建了文件并且没有添加任何东西.我读了《课堂:IO文档》,但我真的听不懂.
but it created file and didn't add anything. I read the Class: IO documentation but I couldn't really get it.
推荐答案
像这样:
class Line
attr_reader :p1, :p2
def initialize point1, point2
@p1 = point1
@p2 = point2
end
end
line = Line.new([1,2], [3,4])
保存line
:
FNAME = 'my_file'
File.open(FNAME, 'wb') {|f| f.write(Marshal.dump(line))}
检索到line1
:
line1 = Marshal.load(File.binread(FNAME))
确认它有效:
line1.p1 # => [1, 2]
这篇关于在Ruby中使用Marshal :: dump进行对象序列化时如何写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文