Project

dig-deep

0.01
No commit activity in last 3 years
No release in over 3 years
Give a hash key, DigDeep will recursively search in the hash and return all values.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
 Dependencies

Development

~> 1.16
~> 12.3.3
~> 3.0
 Project Readme

DigDeep

DigDeep will look up key/value pairs in a nested hash by a given key. It will recursively dig each nested object and return all matching key/values.

Ruby's dig method can perform similar tasks, but you need to specify the path to the target key.

With this gem, you will only need to specify the target key and it will do the digging.

Installation

Add this line to your application's Gemfile:

gem 'dig-deep'

And then execute:

$ bundle

Or install it yourself as:

$ gem install dig-deep

Test

$ bundle exec rspec spec

Usage

Example 1:

Given the following hash:

data = {
  a: {
    b: {
      c: "abc"
    }
  }
}

Ruby .dig:

data.dig(:a, :b, :c)   // "abc"

With DigDeep:

require 'dig-deep'

data.dig_deep(:c)      // "abc"

Example 2:

Dig up all :email from arrays of objects

data = {
  contacts: [{
    name: "John",
    email: "john@example.com"
  }, {
    name: "Mary",
    email: "mary@example.com"
  }],
  work: {
    contacts: [{
      name: "ACME Corp.",
      email: "acme@example.com"
    }, {
      name: "Asdf Inc.",
      email: "asdf@example.com"
    }]
  }
}
require 'dig-deep'

data.dig_deep(:email)  // ["john@example.com", "mary@example.com", "acme@example.com", "asdf@example.com"]

Example 3:

Object with boolean, string, array...

data = {
  :l1 => {
    :l2 => {
      :l3 => {
        :l4a => "Level 4",
        :l4b => {
          :l5a => false,
          :l5b => {
            :l6 => ["apple", "orange"]
          }
        } 
      }
    }
  },
  :l7 => true,
  :l8 => {
    :l9 => 9876
  }
}
require 'dig-deep'

data.dig_deep(:l4a)   // "Level 4"

data.dig_deep(:l5a)   // false

data.dig_deep(:l6)    // ["apple", "orange"]

data.dig_deep(:l9)    // 9876

data.dig_deep(:xyz)   // nil   (returns nil when key is not found)

Example 4:

Object with symbol and string keys

data = {
  :email  => "email+1@example.com",
  :level1 => {
    "email" => "email+2@example.com"
  }
}
require 'dig-deep'

data.dig_deep(:email)   // ["email+1@example.com", "email+2@example.com"]

data.dig_deep('email')  // ["email+1@example.com", "email+2@example.com"]

Contributing

Bug reports and pull requests are welcome!

Fork it, create your new branch, push and create a pull request.

License

The gem is available as open source under the terms of the MIT License.