# Easily Extract Deeply Nested Hash Data in Ruby

> Ruby 2.3 introduced a new method, which is very usful when dealing with deeply nested data in a hash or array. Learn how to add it to your toolbox!

- URL: https://velocitylabs.io/blog/2018/06/20/easily-extract-deeply-nested-hash-data-in-ruby/
- Published: June 20, 2018
- Author: Curtis Miller

Dealing with deeply nested hashes can be a huge pain, but it doesn't need to be.

We’ve all been in the situation where you obtain data in a hash and need to extract some value. For example, you have the following hash, and need to get the innermost value:

```ruby
hash = { first: { second: { third: 'value' } } }
```

You could try:

```ruby
hash[:first][:second][:third] #=> 'value'
```

However, what happens when a `nil` is encountered along the way?

```ruby
hash = {}
hash[:first][:second][:third] #=> NoMethodError: undefined method `[]' for nil:NilClass
```

Throwing an exeption may not be what you want. If you have access to `ActiveSupport` you could use the `try` method:

```ruby
hash.try(:[], :first).try(:[], :second).try(:[], :third) #=> 'value'
```

**Now, I like the `try` method, but this is truly an abomination.**

### Enter Hash#dig

As of Ruby 2.3.0, the `Hash#dig` method makes this so much easier. Take a look!

```ruby
hash = { first: { second: { third: 'value' } } }
hash.dig(:first, :second, :third)                #=> 'value'

hash = { first: { second: nil } }
hash.dig(:first, :second, :third)                #=> nil
```

If a `nil` is encountered at any level, then `nil` is returned.

Note that this also works for [`Array`](http://ruby-doc.org/core-2.5.1/Array.html#method-i-dig) and [`Struct`](http://ruby-doc.org/core-2.5.1/Struct.html#method-i-dig), although I’m not sure they are as useful as the `Hash` method:

```ruby
array = [[['value']]]
array.dig(0, 0, 0)    #=> 'value'
```
