【问题标题】:How to write to file when using Marshal::dump in Ruby for object serialization在 Ruby 中使用 Marshal::dump 进行对象序列化时如何写入文件
【发布时间】:2014-02-26 07:10:14
【问题描述】:

假设我有 Line 类中的对象 line

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

line = Line.new...

如何二进制序列化 line 对象?我试过了:

data = Marshal::dump(line, "path/to/still/unexisting/file")

但是它创建了文件并且没有添加任何东西。我阅读了 Class: IO 文档,但我无法真正理解。

【问题讨论】:

  • Marshal 不是持久存储的好选择,二进制格式取决于您使用的特定 Ruby 版本。最好使用 JSON、YAML、XML 等通用格式...
  • @muistooshort 如果您愿意在 ruby​​ 版本更改时重新创建它,并且您有大量需要保存的数据/变量,那么这是一个不错的选择。它也很快。

标签: ruby serialization marshalling binary-serialization


【解决方案1】:

像这样:

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]

【讨论】:

  • 为什么File.open(FNAME, 'wb') {|f| f.write(Marshal.dump(line))} 运行良好,但使用f = File.open(FNAME, 'wb')f.write(Marshal.dump(line)) 会导致加载时“编组数据太短(ArgumentError)”?
  • @KaRolthas,有趣的问题。答案是当open 与块一起使用时,文件在块执行后关闭。当open 没有块时,您需要在写入后关闭文件(f.close)。如果不关闭文件File.binread(FNAME)会尝试读取打开的文件,导致报错。
猜你喜欢
  • 1970-01-01
  • 2010-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多