问题描述
我有这个ruby脚本,它会生成一个哈希并将其保存到文件中.
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) }
现在我收到此错误:
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?
尽管我在Mac上进行了测试,并且此脚本在Linux中运行,但我尝试使用irb手动进行操作,并且运行良好.他们的行为不应有所不同,对吧?
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?
推荐答案
Ruby没有用于代码的Marshal
格式,仅用于数据.您无法封送Proc
或lambda.
Ruby doesn't have a Marshal
format for code, only for data. You cannot marshal Proc
s or lambdas.
您的apps
哈希具有default_proc
,因为
hsh = Hash.new { some_block }
与
hsh = {}
hsh.default_proc = ->{ some_block }
IOW:您的apps
哈希包含代码,并且代码无法编组.
IOW: your apps
hash contains code, and code cannot marshalled.
这篇关于元帅无法使用默认proc(TypeError)转储哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!