Module: Reading::Util::HashArrayDeepFetch

Defined in:
lib/reading/util/hash_array_deep_fetch.rb

Overview

Similar to Array#dig and Hash#dig but raises an error for not found elements.

More flexible but slightly slower alternative:

keys.reduce(self) { |a, e| a.fetch(e) }

See performance comparisons: fpsvogel.com/posts/2022/ruby-hash-dot-syntax-deep-fetch

Instance Method Summary collapse

Instance Method Details

#deep_fetch(*keys) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/reading/util/hash_array_deep_fetch.rb', line 14

def deep_fetch(*keys)
  case keys.length
  when 1
    fetch(keys[0])
  when 2
    fetch(keys[0]).fetch(keys[1])
  when 3
    fetch(keys[0]).fetch(keys[1]).fetch(keys[2])
  when 4
    fetch(keys[0]).fetch(keys[1]).fetch(keys[2]).fetch(keys[3])
  when 5
    fetch(keys[0]).fetch(keys[1]).fetch(keys[2]).fetch(keys[3]).fetch(keys[4])
  else
    raise FetchDepthExceededError, "#deep_fetch can't fetch that deep!"
  end
end