Ruby:从散列哈希中删除特定键的所有实例

时间:2012-05-20 19:43:08

标签: ruby

我有像

这样的哈希
h = {1 => {"inner" => 45}, 2 => {"inner" => 46}, "inner" => 47}

如何删除包含“内部”键的每一对?
你可以看到一些“内部”对直接出现在h中,而其他对出现在h

请注意,我只想删除“内部”对,所以如果我在上面的哈希上调用我的批量删除方法,我应该

h = {1 => {}, 2 => {}}

由于这些对没有键==“内在”

5 个答案:

答案 0 :(得分:8)

真的,这就是拒绝!适用于:

def f! x
  x.reject!{|k,v| 'inner' == k} if x.is_a? Hash
  x.each{|k,v| f! x[k]}
end

答案 1 :(得分:6)

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

答案 2 :(得分:5)

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

答案 3 :(得分:2)

以下是我提出的建议:

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"}}

答案 4 :(得分:0)

类似的答案,但它是白名单式的方法。对于ruby 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