gpt4 book ai didi

ruby - Marshal 无法使用默认过程转储哈希(TypeError)

转载 作者:数据小太阳 更新时间:2023-10-29 07:21:02 24 4
gpt4 key购买 nike

我有这个 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) }

现在我得到这个错误:

script.rb:53:in `dump': can't dump hash with default proc (TypeError)`

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

我尝试使用 irb 手动完成它并且工作正常,尽管我在 Mac 上测试并且该脚本在 Linux 中运行。他们的行为不应该有所不同,对吧?

最佳答案

Ruby 没有Marshal 代码格式,只有数据格式。您不能编码 Proc 或 lambda。

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

hsh = Hash.new { some_block }

或多或少与

相同
hsh = {}
hsh.default_proc = ->{ some_block }

IOW:您的apps 哈希包含代码,并且无法编码代码。

关于ruby - Marshal 无法使用默认过程转储哈希(TypeError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13360541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com