How do I use Array#dig and Hash#dig introduced in Ruby 2.3?
In our case, NoMethodError
s due to nil
references are by far the most common errors we see in our production environments.
The new Hash#dig
allows you to omit nil
checks when accessing nested elements. Since hashes are best used for when the structure of the data is unknown, or volatile, having official support for this makes a lot of sense.
Let's take your example. The following:
user.dig(:user, :address, :street1)
Is not equivalent to:
user[:user][:address][:street1]
In the case where user[:user]
or user[:user][:address]
is nil
, this will result in a runtime error.
Rather, it is equivalent to the following, which is the current idiom:
user[:user] && user[:user][:address] && user[:user][:address][:street1]
Note how it is trivial to pass a list of symbols that was created elsewhere into Hash#dig
, whereas it is not very straightforward to recreate the latter construct from such a list. Hash#dig
allows you to easily do dynamic access without having to worry about nil
references.
Clearly Hash#dig
is also a lot shorter.
One important point to take note of is that Hash#dig
itself returns nil
if any of the keys turn out to be, which can lead to the same class of errors one step down the line, so it can be a good idea to provide a sensible default. (This way of providing an object which always responds to the methods expected is called the Null Object Pattern.)
Again, in your example, an empty string or something like "N/A", depending on what makes sense:
user.dig(:user, :address, :street1) || ""
One way would be in conjunction with the splat operator reading from some unknown document model.
some_json = JSON.parse( '{"people": {"me": 6, ... } ...}' )
# => "{"people" => {"me" => 6, ... }, ... }
a_bunch_of_args = response.data[:query]
# => ["people", "me"]
some_json.dig(*a_bunch_of_args)
# => 6
It's useful for working your way through deeply nested Hashes/Arrays, which might be what you'd get back from an API call, for instance.
In theory it saves a ton of code that would otherwise check at each level whether another level exists, without which you risk constant errors. In practise you still may need a lot of this code as dig
will still create errors in some cases (e.g. if anything in the chain is a non-keyed object.)
It is for this reason that your question is actually really valid - dig
hasn't seen the usage we might expect. This is commented on here for instance: Why nobody speaks about dig.
To make dig
avoid these errors, try the KeyDial gem, which I wrote to wrap around dig
and force it to return nil/default if any error crops up.