Class: Hash

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

Instance Method Summary collapse

Instance Method Details

#to_2d_hash(opts = {}) ⇒ Hash

Create a two-dimensional copy of the current hash

Parameters:

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :delimiter (String) — default: '_'

    Delimiter to use when concatenating keys

  • :prefix (String) — default: nil

    Key prefix. Set automatically when converting nested hashes recursively. No need to set this manually.

Returns:



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/hash/to_2d_hash.rb', line 8

def to_2d_hash(opts={})
  output = self.class.new
  self.each do |k, v|
    key = opts[:prefix] ? "#{opts[:prefix]}#{opts[:delimiter]||'_'}#{k}" : k
    if v.is_a? Hash
      output.merge! v.to_2d_hash(opts.merge(prefix: key))
    else
      output[key] = v
    end
  end
  output
end