Reputation: 1282
I have a hash yaml
, which is sometimes like:
{"foo" => {"bar" => 10}}
and sometimes like:
{"foo" => nil}
I want to do a certain action depending on whether "bar"
is present.
I write this code:
if yaml["foo"] && yaml["foo"].key?["bar"]
...
I'd like to know if there's an idiomatic way to deal with that conditional, especially the first part where I have to check the existence of the parent key.
Upvotes: 0
Views: 1538
Reputation: 52357
Hash#dig
comes in very handy for cases like yours:
hash = {"foo" => {"bar" => { "baz" => 10}}}
hash.dig('foo', 'bar', 'baz')
#=> 10
Note, that if at any point of dig
ging it returns nil
, the method won't blow up but just return nil
as result:
hash.dig('foo', 'baz')
#=> nil
Upvotes: 2