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

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.

Reply via email to