Sha256: c4591c9f9dea8ba410ad71b98eb8467201bdcb8ae17d0d73ca515f66dae79435

Contents?: true

Size: 1.57 KB

Versions: 12

Compression:

Stored size: 1.57 KB

Contents

class Hash

  # Converts all keys in the Hash to be String values, returning a new Hash.
  # With a from_class parameter, limits conversion to only a certain class of keys.
  # It defaults to nil which convert any key class.
  #
  #   foo = { :name=>'Gavin', :wife=>:Lisa }
  #   foo.variablize_keys    #=>  { "@name"=>"Gavin", "@wife"=>:Lisa }
  #   foo.inspect            #=>  { :name =>"Gavin", :wife=>:Lisa }
  #
  def variablize_keys( of_class=nil )
    self.dup.variablize_keys!( of_class )
  end

  # Synonym for Hash#keys_to_string, but modifies the receiver in place (and returns it).
  # With a from_class parameter, limits conversion to only a certain class of keys.
  # It defaults to nil which convert any key class.
  #
  #   foo = { :name=>'Gavin', :wife=>:Lisa }
  #   foo.variablize_keys!   #=>  { "@name"=>"Gavin", "@wife"=>:Lisa }
  #   foo.inspect            #=>  { "@name"=>"Gavin", "@wife"=>:Lisa }
  #
  def variablize_keys!( of_class=nil )
    raise ArgumentError, "Parameter must be a class" unless of_class.kind_of?(Class) if of_class
    if of_class
      self.each_key do |k|
        if k.respond_to?(:to_s) and k.class == of_class
          k = k.to_s
          nk = k[0,1] != '@' ? k : "@#{k}"
          self[nk]=self.delete(k)
        end
      end
    else
      self.each_key do |k|
        if k.respond_to?(:to_s)
          k = k.to_s
          nk = k[0,1] != '@' ? k : "@#{k}"
          self[nk]=self.delete(k)
        end
      end
    end
    self
  end

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
# TODO

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
facets-1.4.5 lib/facets/core/hash/variablize_keys.rb
facets-1.4.4 lib/facets/core/hash/variablize_keys.rb
facets-1.7.38 lib/facets/core/hash/variablize_keys.rb
facets-1.7.0 lib/facets/core/hash/variablize_keys.rb
facets-1.7.30 lib/facets/core/hash/variablize_keys.rb
facets-1.7.46 lib/facets/core/hash/variablize_keys.rb
facets-1.8.49 lib/facets/core/hash/variablize_keys.rb
facets-1.8.0 lib/facets/core/hash/variablize_keys.rb
facets-1.8.20 lib/facets/core/hash/variablize_keys.rb
facets-1.8.51 lib/facets/core/hash/variablize_keys.rb
facets-1.8.54 lib/facets/core/hash/variablize_keys.rb
facets-1.8.8 lib/facets/core/hash/variablize_keys.rb