vadviktor
7/8/2015 - 4:07 PM

Do you have a deeply nested structures you want 1 value from deep inside? Don’t care if the path is broken? Use digg! I especially love this

Do you have a deeply nested structures you want 1 value from deep inside? Don’t care if the path is broken? Use digg! I especially love this to get deeply nested data out of a JSON response.

# origin: http://thingsinabucket.com/2015/07/01/three_little_hacks/

module Digg
  def digg(*path)
    path.inject(self) do |memo, key|
      (memo.respond_to?(:[]) && (memo[key] || {})) || break
    end
  end
end

Array.send :include, Digg
Hash.send :include, Digg

# Use as
some_complex_json_rsponse.digg('preview', 'thumbnail', 0, 'id')