How can I save an object to a file?

前端 未结 3 2014
深忆病人
深忆病人 2020-12-05 10:27

I would like to save an object to a file, and then read it from the file easily. As a simple example, lets say I have the following 3d array:

m = [[[0, 0, 0]         


        
3条回答
  •  自闭症患者
    2020-12-05 11:04

    YAML and Marshal are the most obvious answers, but depending on what you're planning to do with the data, sqlite3 may be a useful option too.

    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
    

提交回复
热议问题