1

我的哈希:

$settings =
{
  :first_run=>true, :version=>1.01, :game_variables=>{}, :game_switches=>{9=>false}
}

保存代码:

marshal_dump = Marshal.dump($settings)
file = File.new(file_path, 'w')
file.write marshal_dump
file.close

加载代码:

$settings = Marshal.load(File.binread(file_path))

到目前为止,一切仍然有效。但是,只要我将另一个变量添加到 $settings 哈希并保存它,然后尝试加载它:

$settings[:test] = 'woohoo!'
save() # saves the hash to disk
load() # loads the hash from disk

它会引发错误:

Argument error occured. dump format error(0xa)

解决方案:( 感谢 ilan berci)

def dump_settings
    File.open(FILENAME,'w') do|file|
      Marshal.dump($settings, file)
    end
  end

  def load_settings
    $settings = if File.exists?(FILENAME)
      File.open(FILENAME) do|file|
        Marshal.load(file)
      end
      else
        create # custom function that fills the $settings for first use
      end
  end
4

1 回答 1

3

您正在以二进制模式读取文件,但内容并没有像那样被转储。

利用:

$settings = Marshal.load(File.open(file_path))

于 2013-02-20T21:39:11.273 回答