Sha256: b6a6b58778e2d7eac1d69e0be52e91ac4f8efcbbf79e7f22d140c08ffbc96ff2

Contents?: true

Size: 1.1 KB

Versions: 2

Compression:

Stored size: 1.1 KB

Contents

# Copyright (C) 2011 AMEE UK Ltd. - http://www.amee.com
# Released as Open Source Software under the BSD 3-Clause license. See LICENSE.txt for details.

# :title: Class: Hash

class Hash

  # Return a new instance of <i>Hash</i> which represents the same data as
  # <tt>self</tt> but with all keys - including those of sub-hashes - symbolized
  #
  def recursive_symbolize_keys
    new_hash = {}
    self.each_pair do |k,v|
      new_hash[k.to_sym] = value_or_symbolize_value(v)
    end
    new_hash
  end

  # Modify <tt>self</tt> in place, transforming all keys - including those of
  # sub-hashes - in to symbols
  #
  def recursive_symbolize_keys!
    items = {}
    self.each_pair do |k,v|
      value = delete(k)
      items[k] = value_or_symbolize_value(value)
    end
    items
  end

  private

  # Symbolize any hash key or sub-hash key containing within <tt>value</tt>.
  def value_or_symbolize_value(value)
    if value.is_a? Hash
      return value.recursive_symbolize_keys
    elsif value.is_a? Array
      return value.map { |elem| value_or_symbolize_value(elem) }
    else
      return value
    end
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
amee-data-abstraction-2.3.1 lib/core-extensions/hash.rb
amee-data-abstraction-2.3.0 lib/core-extensions/hash.rb