2013-02-20 14 views
1

我的哈希:元帥轉儲文件格式錯誤(是0xA)

$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[:test] = 'woohoo!' 
save() # saves the hash to disk 
load() # loads the hash from disk 

它會引發錯誤:

Argument error occured. dump format error(0xa) 

解決方案: (感謝去宜蘭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 

回答

3

您正在閱讀的文件以二進制模式,但內容沒有被拋棄這樣的。

使用:

$設置= Marshal.load(File.open(FILE_PATH))

+0

對不起。這確實是問題所在。我有2個保存功能,我忘了更換另一個代碼。 – Napoleon 2013-02-21 20:03:14