作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我有这个 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/
我正在为我的应用程序使用 Tank-Auth。我唯一的问题是激活和重置帐户密码。 用于登录、注册、注销;我对这些代码没有问题; $route['login'] = "/auth/login"; $ro
我是一名优秀的程序员,十分优秀!