gpt4 book ai didi

Ruby dig set - 使用 Hash#dig 分配值

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

基本上我想使用 #dig 分配一个数组。

我必须是这样的:

hash = {
:first => {
:second => [1,2,3,4]
}
}

我会使用Hash#dig

hash.dig(:first, :second) = [1,2,3,4]

如何分配这个值?

最佳答案

您可以创建一个表现如您所愿的散列。 Hash.new获取一个 block ,每当键查找失败时调用该 block 。当发生这种情况时,我们可以创建一个空哈希:

hash = Hash.new { |hash, key| hash[key] = Hash.new(&hash.default_proc) }

hash[:first][:second] = [1, 2, 3, 4]

hash # => {:first=>{:second=>[1, 2, 3, 4]}}

请注意,仅仅访问一个不存在的 key 将导致创建一个新的散列:

hash.dig(:a, :b, :c) # => {}

hash # => {:first=>{:second=>[1, 2, 3, 4]}, :a=>{:b=>{:c=>{}}}}

hash[:foo].nil? # => false

关于Ruby dig set - 使用 Hash#dig 分配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56634950/

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