我的哈希:
$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