1 min read

TIL: How to delete a key-value from an arbitrarily deep Ruby hash

by using recursive procs.

Use procs and make them recursive for extra fruitiness.

The Hash#delete_if method takes a proc and, if it returns true, the element will be deleted. Careful: this is a mutating method, operating on the original object and doesn't return a copy.

deep_clean = Proc.new do |k, v| 
  v.delete_if(&deep_clean) if v.kind_of?(Hash)
  k == :delete_me || v.nil? || v.empty?
end

hsh.delete_if(&deep_clean)

Tweak line 3 to get the outcome you need. Becareful of using the &s right when copying the above.