问题
I have this ruby script that generates a hash and saves it to a file.
Sometimes the file doesn't exist or is empty, so I always check the existence of it first. Then I load the old values into my hash and try to save again. I've been struggling with this for a long time now. This is a sample:
newAppName = ARGV[0]
newApp = Hash.new
newApp["url"] = ARGV[1]
newApp["ports"] = ARGV[2].to_i
apps = Hash.new { |h, k| h[k] = Hash.new }
# apps["test"] = {"url" => "www.test.com", "ports" => 3 }
appsFile = '/home/test/data/apps'
if File.exists?(appsFile)
apps = Marshal.load File.read(appsFile)
else
puts "Inserting first app into list..."
end
apps[newAppName] = newApp
serialisedApps = Marshal.dump(apps) # This line is where I get the error
File.open(appsFile, 'w') {|f| f.write(serialisedApps) }
Now I get this error:
script.rb:53:in `dump': can't dump hash with default proc (TypeError)`
What does it mean? Is my hash wrong? How do I fix it?
I tried doing it manually with irb and it was working fine, though I tested on a Mac and this script is running in Linux. They should not behave different, right?
回答1:
Ruby doesn't have a Marshal
format for code, only for data. You cannot marshal Proc
s or lambdas.
Your apps
hash has a default_proc
, because
hsh = Hash.new { some_block }
is more or less the same as
hsh = {}
hsh.default_proc = ->{ some_block }
IOW: your apps
hash contains code, and code cannot marshalled.
来源:https://stackoverflow.com/questions/13360541/marshal-cant-dump-hash-with-default-proc-typeerror