Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
app/deep.rb

Overview

Deep extensions for Hash.

Instance Method Summary collapse

Instance Method Details

#deep_delete(*path) ⇒ Object

Raises:

  • (ArgumentError)


22
23
24
25
26
27
28
29
30
31
32
33
# File 'app/deep.rb', line 22

def deep_delete(*path)
  raise ArgumentError, 'no path specified' if path.empty?
  raise KeyError, "key not found: #{path[0]}" unless key?(path[0])

  if path.size == 1
    delete(path[0])
  else
    raise ArgumentError, "value for key is not a hash: #{path[0]}" unless self.[](path[0]).is_a?(Hash)

    self.[](path[0]).deep_delete(*path[1..])
  end
end

#deep_set(*path, value:) ⇒ Object

Raises:

  • (ArgumentError)


9
10
11
12
13
14
15
16
17
18
19
20
# File 'app/deep.rb', line 9

def deep_set(*path, value:)
  raise ArgumentError, 'no path specified' if path.empty?

  if path.size == 1
    self[path[0]] = value
  else
    raise KeyError, "key not found: #{path[0]}" unless key?(path[0])
    raise ArgumentError, "value for key is not a hash: #{path[0]}" unless self.[](path[0]).is_a?(Hash)

    self.[](path[0]).deep_set(*path[1..], value: value)
  end
end