我的哈希:
$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 hash并保存它然后尝试加载它:
$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
答案 0 :(得分:3)
您正在以二进制模式读取文件,但内容尚未像这样被转储。
使用:
$ settings = Marshal.load(File.open(file_path))