加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Ruby中使用Marshal :: dump进行对象序列化时如何写入文件

发布时间:2020-12-16 20:55:57 所属栏目:百科 来源:网络整理
导读:假设我有类Line的对象行: class Line def initialize point1,point2 @p1 = point1 @p2 = point2 endend line = Line.new … 如何对行对象进行二进制序列化?我尝试过: data = Marshal::dump(line,"path/to/still/unexisting/file") 但它创建了文件,并没有
假设我有类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]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读