我有一个像
h = {1 => {"inner" => 45}, 2 => {"inner" => 46}, "inner" => 47}
如何删除包含“inner”键的每一对?
您可以看到一些“内部”对直接出现在其中,h
而另一些则成对出现在h
请注意,我只想删除“内部”对,所以如果我在上面的哈希上调用我的批量删除方法,我应该得到
h = {1 => {}, 2 => {}}
由于这些对没有键 == "inner"
我有一个像
h = {1 => {"inner" => 45}, 2 => {"inner" => 46}, "inner" => 47}
如何删除包含“inner”键的每一对?
您可以看到一些“内部”对直接出现在其中,h
而另一些则成对出现在h
请注意,我只想删除“内部”对,所以如果我在上面的哈希上调用我的批量删除方法,我应该得到
h = {1 => {}, 2 => {}}
由于这些对没有键 == "inner"
真的,这就是拒绝!是为了:
def f! x
x.reject!{|k,v| 'inner' == k} if x.is_a? Hash
x.each{|k,v| f! x[k]}
end
def f x
x.inject({}) do |m, (k, v)|
v = f v if v.is_a? Hash # note, arbitrarily recursive
m[k] = v unless k == 'inner'
m
end
end
p f h
更新: 略有改进...
def f x
x.is_a?(Hash) ? x.inject({}) do |m, (k, v)|
m[k] = f v unless k == 'inner'
m
end : x
end
def except_nested(x,key)
case x
when Hash then x = x.inject({}) {|m, (k, v)| m[k] = except_nested(v,key) unless k == key ; m }
when Array then x.map! {|e| except_nested(e,key)}
end
x
end
这是我想出的:
class Hash
def deep_reject_key!(key)
keys.each {|k| delete(k) if k == key || self[k] == self[key] }
values.each {|v| v.deep_reject_key!(key) if v.is_a? Hash }
self
end
end
适用于 Hash 或 HashWithIndifferentAccess
> x = {'1' => 'cat', '2' => { '1' => 'dog', '2' => 'elephant' }}
=> {"1"=>"cat", "2"=>{"1"=>"dog", "2"=>"elephant"}}
> y = x.with_indifferent_access
=> {"1"=>"cat", "2"=>{"1"=>"dog", "2"=>"elephant"}}
> x.deep_reject_key!(:"1")
=> {"1"=>"cat", "2"=>{"1"=>"dog", "2"=>"elephant"}}
> x.deep_reject_key!("1")
=> {"2"=>{"2"=>"elephant"}}
> y.deep_reject_key!(:"1")
=> {"2"=>{"2"=>"elephant"}}
类似的答案,但它是一种白名单类型的方法。对于红宝石 1.9+
# recursive remove keys
def deep_simplify_record(hash, keep)
hash.keep_if do |key, value|
if keep.include?(key)
deep_simplify_record(value, keep) if value.is_a?(Hash)
true
end
end
end
hash = {:a => 1, :b => 2, :c => {:a => 1, :b => 2, :c => {:a => 1, :b => 2, :c => 4}} }
deep_simplify_record(hash, [:b, :c])
# => {:b=>2, :c=>{:b=>2, :c=>{:b=>2, :c=>4}}}
这里还有一些我喜欢用于哈希的其他方法。 https://gist.github.com/earlonrails/2048705