This question already has an answer here:
I'm working a little utility written in ruby that makes extensive use of nested hashes. Currently, I'm checking access to nested hash elements as follows:
structure = { :a => { :b => 'foo' }}
# I want structure[:a][:b]
value = nil
if structure.has_key?(:a) && structure[:a].has_key?(:b) then
value = structure[:a][:b]
end
Is there a better way to do this? I'd like to be able to say:
value = structure[:a][:b]
And get nil
if :a is not a key in structure
, etc.
Traditionally, you really had to do something like this:
However, Ruby 2.3 added a feature that makes this way more graceful:
There is a gem called
ruby_dig
that will back-patch this for you.I think one of the most readable solutions is using Hashie:
Ruby 2.3.0 introduced a new method called
dig
on bothHash
andArray
that solves this problem entirely.It returns
nil
if the key is missing at any level.If you are using a version of Ruby older than 2.3, you can use the
ruby_dig
gem or implement it yourself:Not that I would do it, but you can Monkeypatch in
NilClass#[]
:Go with @DigitalRoss's answer. Yes, it's more typing, but that's because it's safer.
I made rubygem for this. Try vine.
Install:
Usage: