Dig on Ruby 2.3

Amongst the additions to Ruby on the 2.3.0 release there's the dig method on objects of the type Hash, Array or Struct.

This method allows you to access deeply nested data on either of these data structures in a safe way.

For example, imagine you have a structure like the following one.

post = {  
  text: 'string',

  user: {
    name: 'string'
  }
}

Now, if you want to access the name of the user who created the post, you may do something like:

name = post[:user][:name]  

This is all good if you're sure that a post always has a key named user pointing to a hash. But if there's a possible scenario where you may get nil as the user, this will crash. So, you might write something like:

name = post[:user][:name] if post[:user]

# or

name = post[:user] && post[:name][:user]  

This works but it could look a lot nicer. Using dig this code code be rewritten as:

name = post.dig :user, :name  

Dig works by navigating through the data structures that result from fetching each key starting at the original object. And the best part is that it stops when it finds a nil value, making it a very handy tool to have under your sleeve.

You can also use it with more complex data. Lets say you have something like the following.

Tag = Struct.new(:name)

post = {  
  text: 'string',

  user: { 
    name: 'string'
  },

  tags: [Tag.new('Ruby'), Tag.new('Postgres')]
}

If you want to access the name of the first tag in the post, you can just do:

post.dig :tags, 0, :name  

Pretty cool!

If you want to have a deeper look into how this is implemented behind the scenes, this is a good place to start.