假设我有Line类的对象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: IO 文档,但我无法真正理解它。
最佳答案
像这样:
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]
关于ruby - 在 Ruby 中使用 Marshal::dump 进行对象序列化时如何写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21516511/