Sha256: cff2204e51a1dcc3cc489e6e74dd181836cddffaac1d7a6644465b21955b4fa9

Contents?: true

Size: 1.09 KB

Versions: 11

Compression:

Stored size: 1.09 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!
    self.each_pair do |k,v|
      value = delete(k)
      self[k.to_sym] = value_or_symbolize_value(value)
    end
    self
  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

11 entries across 11 versions & 1 rubygems

Version Path
amee-3.2.1 lib/amee/core-extensions/hash.rb
amee-3.2.0 lib/amee/core-extensions/hash.rb
amee-4.1.6 lib/amee/core-extensions/hash.rb
amee-4.1.5 lib/amee/core-extensions/hash.rb
amee-4.1.4 lib/amee/core-extensions/hash.rb
amee-4.1.3 lib/amee/core-extensions/hash.rb
amee-3.1.2 lib/amee/core-extensions/hash.rb
amee-3.1.1 lib/amee/core-extensions/hash.rb
amee-4.1.2 lib/amee/core-extensions/hash.rb
amee-4.1.1 lib/amee/core-extensions/hash.rb
amee-4.1.0 lib/amee/core-extensions/hash.rb