我想将对象保存到文件中,然后轻松地从文件中读取它。举一个简单的例子,可以说我有以下的三维数组:如何将对象保存到文件?
m = [[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]]
有没有我可以用它来实现这一点没有编程解析器来解释从文件中的数据一个简单的Ruby API?在这个例子中,我认为它很容易,但随着对象变得越来越复杂,让对象持久化变得烦人。
我想将对象保存到文件中,然后轻松地从文件中读取它。举一个简单的例子,可以说我有以下的三维数组:如何将对象保存到文件?
m = [[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]]
有没有我可以用它来实现这一点没有编程解析器来解释从文件中的数据一个简单的Ruby API?在这个例子中,我认为它很容易,但随着对象变得越来越复杂,让对象持久化变得烦人。
你需要序列化对象之前,你可以将它们保存到一个文件和反序列化他们获取他们回来。如Cory所述,2个标准序列化库被广泛使用,Marshal
和YAML
。
Marshal
和YAML
分别使用方法dump
和load
分别进行序列化和反序列化。
这里是你如何使用它们:
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文档中找到。
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
JSON也会这样做。 – 2010-11-30 03:27:09
Marshal并不是持久化的好工具,格式取决于Ruby版本,并且无法在新的Rubies中解码较旧的Marshal格式。 [“在正常使用中,封送处理只能加载使用相同主要版本号和相同或更低次版本号编写的数据。”](http://ruby-doc.org/core/Marshal.html)。 – 2015-04-06 21:40:34