How to write to file when using Marshal::dump in Ruby for object serialization

自闭症网瘾萝莉.ら 提交于 2019-12-18 04:30:11

问题


Lets say I have the object line from class 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")

but it created file and didn't add anything. I read the Class: IO documentation but I couldn't really get it.


回答1:


Like this:

class Line
  attr_reader :p1, :p2
  def initialize point1, point2
    @p1 = point1
    @p2 = point2
  end
end

line = Line.new([1,2], [3,4])

Save line:

FNAME = 'my_file'

File.open(FNAME, 'wb') {|f| f.write(Marshal.dump(line))}

Retrieve into line1:

line1 = Marshal.load(File.binread(FNAME))

Confirm it works:

line1.p1 # => [1, 2]


来源:https://stackoverflow.com/questions/21516511/how-to-write-to-file-when-using-marshaldump-in-ruby-for-object-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!