Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/deep_hash.rb

Class Method Summary collapse

Class Method Details

.deep(depth = nil, &block) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
# File 'lib/deep_hash.rb', line 4

def self.deep(depth = nil, &block)
  raise "Need a number for depth" unless depth.nil? || depth.respond_to?(:to_i)
  if depth.nil?
    raise "Cannot use a block with nil depth." if block_given?
    return Hash.new { |k, v| k[v] = Hash.deep(nil) }
  end
  depth = depth.to_i
  raise "Need non-negative depth" if depth < 0
  return block_given? ? Hash.new { |k, v| k[v] = block.call } : {} if depth.zero?
  Hash.new { |k, v| k[v] = Hash.deep(depth - 1, &block) }
end