ngw
ngw

Reputation: 1282

Checking a nested hash key

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

Answers (1)

Andrey Deineko
Andrey Deineko

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 digging it returns nil, the method won't blow up but just return nil as result:

hash.dig('foo', 'baz')
#=> nil

Upvotes: 2

Related Questions