gpt4 book ai didi

Ruby - 用嵌套值优雅地替换散列值(说明)

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

我正在使用的散列有一个散列值,它始终包含 ID、名称和描述。我对保留 ID 或名称不感兴趣,只想用相应的描述替换每个哈希值。

代码

hsh['nested']['entries']['addr'] = hsh['nested']['entries']['addr']['description']
hsh['nested']['entries']['port'] = hsh['nested']['entries']['port']['description']
hsh['nested']['entries']['protocol'] = hsh['nested']['entries']['protocol']['description']
hsh['nested']['entries']['type'] = hsh['nested']['entries']['type']['description']
... (many more)

这工作正常,但不是很优雅——实际上,我有 20 个条目/代码行来完成工作。

哈希值的结构(对于hsh['nested']['entries']['addr'])

{ "id" => "27", "name" => "Instance", "description" => "**This is what I need.**" }

以上面第一行代码为例,最终结果就是hsh['nested']['entries']['addr']的值变成了* *这就是我需要的。**

实现这一目标的优雅方式是什么?

最佳答案

hsh = { 'nested'=>
{ 'entries'=>
{
'addr'=>{ "id" => "1", "description"=>"addr" },
'port'=>{ "id" => "2", "description"=>"port" },
'cats'=>{ "id" => "3", "description"=>"dogs" },
'type'=>{ "id" => "4", "description"=>"type" }
}
}
}

keys_to_replace = ["addr", "port", "type"]

hsh['nested']['entries'].tap { |h| keys_to_replace.each { |k| h[k]=h[k]["description"] }
#=> { "addr"=>"addr",
# "port"=>"port",
# "cats"=>{"id"=>"3", "description"=>"dogs"},
# "type"=>"type"
# }

hsh
#=> {"nested"=>
# { "entries"=>
# { "addr"=>"addr",
# "port"=>"port",
# "cats"=>{"id"=>"3", "description"=>"dogs"},
# "type"=>"type"
# }
# }
# }

关于Ruby - 用嵌套值优雅地替换散列值(说明),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37753220/

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