Hello,
I wanted to see what people thought about adding a "deep_assoc" method to Hash in core_ext.
Given a hash like this:
hash = {a: {b: {c: :d}}}
Its usage would look like this:
hash.deep_assoc(:a, :b, :c)
# => :d
hash.deep_assoc(:a, :e, :f)
# => nil
It is basically a much cleaner way to avoid this pattern:
hash.try(:[], :a).try(:[], :b).try(:[], :c)
It is the one thing which I find myself continually missing in Hash.
A basic implementation looks like this:
class Hash
def deep_assoc(*keys)
current = keys.shift
return self[current] if keys.empty?
return nil unless self[current].is_a?(Hash)
self[current].deep_assoc(keys)
end
end
Please let me know your thoughts.
Thanks!
Micah Buckley-Farlee