2010-11-30 570 views
19

我想將對象保存到文件中,然後輕鬆地從文件中讀取它。舉一個簡單的例子,可以說我有以下的三維數組:如何將對象保存到文件?

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

有沒有我可以用它來實現這一點沒有編程解析器來解釋從文件中的數據一個簡單的Ruby API?在這個例子中,我認爲它很容易,但隨着對象變得越來越複雜,讓對象持久化變得煩人。

回答

14
+3

JSON也會這樣做。 – 2010-11-30 03:27:09

+2

Marshal並不是持久化的好工具,格式取決於Ruby版本,並且無法在新的Rubies中解碼較舊的Marshal格式。 [「在正常使用中,封送處理只能加載使用相同主要版本號和相同或更低次版本號編寫的數據。」](http://ruby-doc.org/core/Marshal.html)。 – 2015-04-06 21:40:34

45

你需要序列化對象之前,你可以將它們保存到一個文件和反序列化他們獲取他們回來。如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文檔中找到。

4

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 
相關問題