Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class Hash
# way too clever!
# but oh-so-useful...
# http://thirtysixthspan.com/posts/hash-tricks-in-ruby
# can be used like so:
# x = Hash.new_recursive
# x[:foo][:bar][:baz] = "hello world"
def self.new_recursive
Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
end
# and *because* it's too clever:
# https://stackoverflow.com/a/31822407
def strip_recursive(hash)
hash.each_with_object({}) do |(k, v), h|
if(v.is_a?(Hash))
ch = strip_recursive(v)
h[k] = ch if(!ch.empty?)
elsif(v.is_a?(Array))
h[k] = v.map do |e|
e.is_a?(Hash) ? strip_recursive(e) : e
end
else
h[k] = v
end
end
end; def strip_recursive!
self = strip_recursive(self)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.