如何将对象保存到文件?

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

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

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

见Marshal: http : //ruby-doc.org/core/classes/Marshal.html

-要么-

YAML: http : //www.ruby-doc.org/core/classes/YAML.html

您需要先序列化对象,然后才能将它们保存到文件中并对其进行反序列化以将其检索回来。 正如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文档中找到。

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