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.
You could just build a Hash subclass with an extra variadic method for digging all the way down with appropriate checks along the way. Something like this (with a better name of course):
Then just use
Thing
s instead of hashes:In my case, I needed a two-dimensional matrix where each cell is a list of items.
I found this technique which seems to work. It might work for the OP:
The output is:
This monkey patch function for Hash should be easiest (at least for me). It also doesn't alter structure i.e. changing
nil
's to{}
. It would still also apply even if you're reading a tree from a raw source e.g. JSON. It also doesn't need to produce empty hash objects as it goes or parse a string.rescue nil
was actually a good easy solution for me as I'm brave enough for such a low risk but I find it to essentially have a drawback with performance.Example:
What's also good is that you can play around saved arrays with it: