Sha256: e1cefdc81db4726a9dd06feb32b0a3ecb0895047aed8c5893de6f1daa4d0f4b9

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-data-abstraction-2.2.2 lib/core-extensions/hash.rb
amee-data-abstraction-2.2.1 lib/core-extensions/hash.rb
amee-data-abstraction-2.2.0 lib/core-extensions/hash.rb
amee-data-abstraction-1.3.1 lib/core-extensions/hash.rb
amee-data-abstraction-1.3.0 lib/core-extensions/hash.rb
amee-data-abstraction-2.1.1 lib/core-extensions/hash.rb
amee-data-abstraction-2.1.0 lib/core-extensions/hash.rb
amee-data-abstraction-1.2.0 lib/core-extensions/hash.rb
amee-data-abstraction-2.0.0 lib/core-extensions/hash.rb
amee-data-abstraction-1.1.0 lib/core-extensions/hash.rb
amee-data-abstraction-1.0.0 lib/core-extensions/hash.rb