Module: Diggable

Defined in:
lib/mug/diggable.rb

Overview

Extend any class or object that implements a #[] method, to also have #dig

Instance Method Summary collapse

Instance Method Details

#dig(*idx) ⇒ Object?

Extracts the nested value specified by the sequence of idx objects by calling dig at each step, returning nil if any intermediate step is nil.

Examples:

require 'mug/diggable'
class Config
  include Diggable
  def [](key); {a: {b: 42}}[key]; end
end
Config.new.dig(:a, :b)  #=> 42

Parameters:

  • idx (Array)

    the sequence of keys/indices to dig into

Returns:

  • (Object, nil)

    the nested value, or nil if not found



23
24
25
26
27
# File 'lib/mug/diggable.rb', line 23

def dig *idx
  inner = self[idx.shift]
  return inner if idx.empty? || inner.nil?
  inner.dig(*idx)
end