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

≯℡__Kan透↙ 提交于 2019-11-29 05:18:35

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