Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

I have a hash like

h = {1 => {"inner" => 45}, 2 => {"inner" => 46}, "inner" => 47}

How do I delete every pair that contains the key "inner"?
You can see that some of the "inner" pairs appear directly in h while others appear in pairs in h

Note that I only want to delete the "inner" pairs, so if I call my mass delete method on the above hash, I should get

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

Since these pairs don't have a key == "inner"

like image 423
MxLDevs Avatar asked May 20 '12 19:05

MxLDevs


People also ask

How do you remove an item from a hash?

The delete function is the only way to remove a specific entry from a hash. Once you've deleted a key, it no longer shows up in a keys list or an each iteration, and exists will return false for that key.

Can a hash have duplicate keys Ruby?

Short answer is no, hashes need to have unique keys.


2 Answers

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

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 : x
end
like image 195
DigitalRoss Avatar answered Oct 13 '22 20:10

DigitalRoss


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
like image 29
Miguel Sancho Fernández Avatar answered Oct 13 '22 18:10

Miguel Sancho Fernández