Marshal can't dump hash with default proc (TypeError)

放肆的年华 提交于 2019-12-22 09:13:44

问题


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 Procs 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!