From: sawadatsuyoshi@...
Date: 2015-11-28T14:38:32+00:00
Subject: [ruby-core:71720] [Ruby trunk - Feature #11747] "bury" feature, similar to 'dig' but opposite

Issue #11747 has been updated by Tsuyoshi Sawada.


>  inferred from the what the user is passing (such as a symbol or string for a hash or an integer for an array)

I don't think this is a good idea. I think it should rather depend on the class of the receiver.

    {}.bury(:users, 0, :name, 'Matz') # => {:users => {0 => {:name => "Matz"}}}
    [].bury(:users, 0, :name, 'Matz') # => error
    {}.bury(0, 1, 2, :foo) # => {0 => {1 => {2 => :foo}}}
    [].bury(0, 1, 2, :foo) # => [[nil, [nil, nil, :foo]]]

and similar for struct.

----------------------------------------
Feature #11747: "bury" feature, similar to 'dig' but opposite 
https://bugs.ruby-lang.org/issues/11747#change-55126

* Author: damien sutevski
* Status: Feedback
* Priority: Normal
* Assignee: Yukihiro Matsumoto
----------------------------------------
In Matz's recent Rubyconf talk, he used this example for the new 'dig' feature coming in Ruby 2.3:

~~~ruby
# we want this
data[:users][0][:name]

# we can do this w/o nil errors
data.dig(:users, 0, :name)
~~~

What I'm proposing is a 'bury' feature that is the opposite of 'dig' in a sense. It inserts a value at an arbitrary depth, for example:

~~~ruby
data.bury(:users, 0, :name, 'Matz')
~~~

This will create a nested hash or an array automatically at each step if it doesn't already exist, and that can be inferred from the what the user is passing (such as a symbol or string for a hash or an integer for an array). It's similar to autovivification but more powerful!

This behavior is very common, at least in my experience, so a dry method built into Ruby would be awesome! 



-- 
https://bugs.ruby-lang.org/