gpt4 book ai didi

ruby - 使用 block 构造函数序列化哈希

转载 作者:数据小太阳 更新时间:2023-10-29 08:04:22 26 4
gpt4 key购买 nike

这是一段代码

myHash = Hash.new {|h, k| h[k] = []}
myHash[5] << 1 # example operation
Marshal.dump(myHash)

当我试图用任意键操作它时,我经常使用它,我不想明确地写这样的东西

myHash = Hash.new
myHash[5] ||= [] # initialize it first, if needed
myHash[5] << 1 # example operation
Marshal.dump(myHash)

虽然只有一行代码不同,但对我来说使用 block 版本看起来更干净一些。

但是在序列化过程中出现了问题

in `dump: can't dump hash with default proc (TypeError)

有没有办法在继续使用构造函数的 block 形式的同时将其序列化?还是我必须坚持在尝试对哈希进行操作之前显式检查和初始化任何值?

我会说不,因为没有真正的方法让 ruby​​ 确定在没有传入原始 proc 的情况下缺少 key 时散列应如何自动生成值。

最佳答案

在转储哈希之前删除默认行为。

myHash = Hash.new {|h, k| h[k] = []}
myHash[5] << 1
myHash.default = nil
Marshal.dump(myHash)

或者,因为您似乎对保留垂直空间感兴趣:

myHash = Hash.new {|h, k| h[k] = []}
myHash[5] << 1
Marshal.dump(myHash.tap {|h| h.default = nil })

但是,这会永久更改散列,使其不再具有默认值。如果这让您感到困扰,但暂时复制您的哈希的顶层不会,请放入 .dup:

Marshal.dump(myHash.dup.tap {|h| h.default = nil })

现在原始哈希的默认行为保持不变。

关于ruby - 使用 block 构造函数序列化哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21812875/

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