Ruby: Deleting all instances of a particular key from hash of hashes Ruby: Deleting all instances of a particular key from hash of hashes ruby ruby

Ruby: Deleting all instances of a particular key from hash of hashes


Really, this is what reject! is for:

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  endendp f h

Update: slightly improved...

def f x  x.is_a?(Hash) ? x.inject({}) do |m, (k, v)|    m[k] = f v unless k == 'inner'    m  end : xend


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  xend