Marshal无法使用默认proc(TypeError)转储哈希

Apo*_*llo 4 ruby marshalling

我有这个ruby脚本生成一个哈希并将其保存到文件中.

有时文件不存在或为空,所以我总是首先检查它的存在.然后我将旧值加载到我的哈希值并尝试再次保存.我一直在努力解决这个问题很长一段时间.这是一个示例:

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) }
Run Code Online (Sandbox Code Playgroud)

现在我收到这个错误:

script.rb:53:in `dump': can't dump hash with default proc (TypeError)`
Run Code Online (Sandbox Code Playgroud)

这是什么意思?我的哈希错了吗?我如何解决它?

我尝试使用irb手动完成它并且它工作正常,但我在Mac上测试并且此脚本在Linux中运行.他们不应该表现不同,对吧?

Jör*_*tag 17

Ruby没有Marshal代码格式,只有数据格式.你不能编组Procs或lambdas.

你的apps哈希有一个default_proc,因为

hsh = Hash.new { some_block }
Run Code Online (Sandbox Code Playgroud)

或多或少是一样的

hsh = {}
hsh.default_proc = ->{ some_block }
Run Code Online (Sandbox Code Playgroud)

IOW:您的apps哈希包含代码,代码无法编组.