如何从Rails的哈希列表中删除嵌套键 [英] How to remove nested keys from a hash list in Rails
问题描述
我现在正尝试几个小时,以删除哈希列表的嵌套哈希键. 我看到许多解决方案的非嵌套哈希看起来像这样:
I am now trying for some hours to remove a nested hash key of a hash list. I saw many solution non-nested hashs wich looks like this:
sample_hash = {"key1" => "value1", "key2" => "value2"}
sample_hash.except("key1")
结果是:
{"key2"=>"value2"}
但是,如果我尝试在带有嵌套键的哈希上使用except方法,那么它将无法正常工作. 这是我的代码:
But if I try to use the except method on a hash with nested key then it doesn't work. Here my code:
nested_hash = {"key1"=>"value1", "key2"=>{
"nested_key1"=>"nestedvalue1",
"nested_key2"=>"nestedvalue2"
}
}
nested_hash.except("nested_key2")
exception()方法将返回nested_hash,而不进行任何更改.我一直在寻找一种解决方案,如何将嵌套的哈希键传递给except方法,但找不到任何东西.甚至可以将嵌套键传递给此方法,还是应该使用其他方法从哈希列表中删除嵌套哈希键?
The except() method returns the nested_hash without any changes. I have looked for a solution how I can pass nested hash-keys to the except method, but couldn't find anything. Is it even possible to pass nested keys to this method or should I use some other method which deletes a nested hash key from my hash list?
推荐答案
有关
Hash[nested_hash.map {|k,v| [k,(v.respond_to?(:except)?v.except("nested_key2"):v)] }]
=> {"key1"=>"value1", "key2"=>{"nested_key1"=>"nestedvalue1"}}
哦.
这篇关于如何从Rails的哈希列表中删除嵌套键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!