如何将对象保存到文件?

时间:2010-11-30 03:12:26

标签: ruby json serialization marshalling yaml

我想将对象保存到文件中,然后轻松地从文件中读取它。举个简单的例子,假设我有以下3d数组:

m = [[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]],
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]]

我是否可以使用简单的Ruby API来实现此目的,而无需编写解析器来解释文件中的数据?在示例中,我给它很简单,但随着对象变得更加复杂,使对象持久化会很烦人。

3 个答案:

答案 0 :(得分:51)

您需要序列化对象,然后才能将它们保存到文件中并反序列化它们以将其检索回来。正如Cory所提到的,2个标准序列化库被广泛使用,MarshalYAML

MarshalYAML都使用方法dumpload分别进行序列化和反序列化。

以下是如何使用它们的方法:

m = [
     [
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0]
     ],
     [
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0]
     ]
    ]

# Quick way of opening the file, writing it and closing it
File.open('/path/to/yaml.dump', 'w') { |f| f.write(YAML.dump(m)) }
File.open('/path/to/marshal.dump', 'wb') { |f| f.write(Marshal.dump(m)) }

# Now to read from file and de-serialize it:
YAML.load(File.read('/path/to/yaml.dump'))
Marshal.load(File.read('/path/to/marshal.dump'))

您需要注意与文件读/写相关的文件大小和其他怪癖。

更多信息,当然可以在API文档中找到。

答案 1 :(得分:15)

答案 2 :(得分:3)

YAML和Marshal是最明显的答案,但根据您计划对数据执行的操作,sqlite3也可能是一个有用的选项。

require 'sqlite3'

m = [[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]],
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]]

db=SQLite3::Database.new("demo.out")
db.execute("create table data (x,y,z,value)")
inserter=db.prepare("insert into data (x,y,z,value) values (?,?,?,?)")
m.each_with_index do |twod,z|
  twod.each_with_index do |row,y|
    row.each_with_index do |val,x|
      inserter.execute(x,y,z,val)
    end
  end
end