Class: Hash

### Home Classes Methods

### In Files

- lib/active_support/core_ext/array/extract_options.rb
- lib/active_support/core_ext/hash/conversions.rb
- lib/active_support/core_ext/hash/deep_dup.rb
- lib/active_support/core_ext/hash/deep_merge.rb
- lib/active_support/core_ext/hash/diff.rb
- lib/active_support/core_ext/hash/except.rb
- lib/active_support/core_ext/hash/indifferent_access.rb
- lib/active_support/core_ext/hash/keys.rb
- lib/active_support/core_ext/hash/reverse_merge.rb
- lib/active_support/core_ext/hash/slice.rb
- lib/active_support/core_ext/object/blank.rb
- lib/active_support/core_ext/object/to_param.rb
- lib/active_support/core_ext/object/to_query.rb
- lib/active_support/json/encoding.rb

### Parent

Object

### Methods

- ::from_trusted_xml
- ::from_xml
- #assert_valid_keys
- #deep_dup
- #deep_merge
- #deep_merge!
- #diff
- #encode_json
- #except
- #except!
- #extract!
- #extractable_options?
- #nested_under_indifferent_access
- #reverse_merge
- #reverse_merge!
- #reverse_update
- #slice
- #slice!
- #stringify_keys
- #stringify_keys!
- #symbolize_keys
- #symbolize_keys!
- #to_options
- #to_options!
- #to_param
- #to_query
- #to_xml
- #with_indifferent_access

### Class/Module Index

Quicksearch

- ActiveSupport
- ActiveSupport::Autoload
- ActiveSupport::BacktraceCleaner
- ActiveSupport::Base64
- ActiveSupport::BasicObject
- ActiveSupport::Benchmarkable
- ActiveSupport::BufferedLogger
- ActiveSupport::BufferedLogger::Severity
- ActiveSupport::Cache
- ActiveSupport::Cache::Entry
- ActiveSupport::Cache::FileStore
- ActiveSupport::Cache::MemCacheStore
- ActiveSupport::Cache::MemoryStore
- ActiveSupport::Cache::NullStore
- ActiveSupport::Cache::Store
- ActiveSupport::Cache::Strategy
- ActiveSupport::Cache::Strategy::LocalCache
- ActiveSupport::Cache::Strategy::LocalCache::LocalStore
- ActiveSupport::Callbacks
- ActiveSupport::Callbacks::ClassMethods
- ActiveSupport::Concern
- ActiveSupport::Configurable
- ActiveSupport::Configurable::ClassMethods
- ActiveSupport::Configurable::Configuration
- ActiveSupport::Dependencies
- ActiveSupport::Dependencies::ClassCache
- ActiveSupport::Dependencies::WatchStack
- ActiveSupport::Deprecation
- ActiveSupport::DescendantsTracker
- ActiveSupport::Duration
- ActiveSupport::FileUpdateChecker
- ActiveSupport::FileWatcher
- ActiveSupport::FileWatcher::Backend
- ActiveSupport::Gzip
- ActiveSupport::Gzip::Stream
- ActiveSupport::HashWithIndifferentAccess
- ActiveSupport::HashWithIndifferentAccess
- ActiveSupport::Inflector
- ActiveSupport::Inflector::Inflections
- ActiveSupport::InheritableOptions
- ActiveSupport::JSON
- ActiveSupport::JSON::Encoding
- ActiveSupport::JSON::Encoding::CircularReferenceError
- ActiveSupport::JSON::Encoding::Encoder
- ActiveSupport::JSON::Variable
- ActiveSupport::LogSubscriber
- ActiveSupport::LogSubscriber::TestHelper
- ActiveSupport::LogSubscriber::TestHelper::MockLogger
- ActiveSupport::Memoizable
- ActiveSupport::Memoizable::InstanceMethods
- ActiveSupport::MessageEncryptor
- ActiveSupport::MessageEncryptor::InvalidMessage
- ActiveSupport::MessageVerifier
- ActiveSupport::MessageVerifier::InvalidSignature
- ActiveSupport::Multibyte
- ActiveSupport::Multibyte::Chars
- ActiveSupport::Multibyte::EncodingError
- ActiveSupport::Multibyte::Unicode
- ActiveSupport::Multibyte::Unicode::Codepoint
- ActiveSupport::Multibyte::Unicode::UnicodeDatabase
- ActiveSupport::Notifications
- ActiveSupport::Notifications::Event
- ActiveSupport::Notifications::Fanout
- ActiveSupport::Notifications::Instrumenter
- ActiveSupport::OrderedHash
- ActiveSupport::OrderedOptions
- ActiveSupport::Railtie
- ActiveSupport::Rescuable
- ActiveSupport::Rescuable::ClassMethods
- ActiveSupport::SafeBuffer
- ActiveSupport::SafeBuffer::SafeConcatError
- ActiveSupport::StringInquirer
- ActiveSupport::TaggedLogging
- ActiveSupport::TestCase
- ActiveSupport::Testing
- ActiveSupport::Testing::Assertions
- ActiveSupport::Testing::Declarative
- ActiveSupport::Testing::Isolation
- ActiveSupport::Testing::Isolation::Forking
- ActiveSupport::Testing::Isolation::MiniTest
- ActiveSupport::Testing::Isolation::Subprocess
- ActiveSupport::Testing::Isolation::TestUnit
- ActiveSupport::Testing::Pending
- ActiveSupport::Testing::Performance
- ActiveSupport::Testing::Performance::Benchmarker
- ActiveSupport::Testing::Performance::ForClassicTestUnit
- ActiveSupport::Testing::Performance::ForMiniTest
- ActiveSupport::Testing::Performance::Metrics
- ActiveSupport::Testing::Performance::Metrics::Amount
- ActiveSupport::Testing::Performance::Metrics::Base
- ActiveSupport::Testing::Performance::Metrics::CpuTime
- ActiveSupport::Testing::Performance::Metrics::DigitalInformationUnit
- ActiveSupport::Testing::Performance::Metrics::GcRuns
- ActiveSupport::Testing::Performance::Metrics::GcTime
- ActiveSupport::Testing::Performance::Metrics::Memory
- ActiveSupport::Testing::Performance::Metrics::Objects
- ActiveSupport::Testing::Performance::Metrics::ProcessTime
- ActiveSupport::Testing::Performance::Metrics::Time
- ActiveSupport::Testing::Performance::Metrics::UserTime
- ActiveSupport::Testing::Performance::Metrics::WallTime
- ActiveSupport::Testing::Performance::Performer
- ActiveSupport::Testing::Performance::Profiler
- ActiveSupport::Testing::ProxyTestResult
- ActiveSupport::Testing::RemoteError
- ActiveSupport::Testing::SetupAndTeardown
- ActiveSupport::Testing::SetupAndTeardown::ClassMethods
- ActiveSupport::Testing::SetupAndTeardown::ForClassicTestUnit
- ActiveSupport::Testing::SetupAndTeardown::ForMiniTest
- ActiveSupport::TimeWithZone
- ActiveSupport::TimeZone
- ActiveSupport::XmlMini
- ActiveSupport::XmlMini_LibXMLSAX
- ActiveSupport::XmlMini_LibXMLSAX::HashBuilder
- ActiveSupport::XmlMini_NokogiriSAX
- ActiveSupport::XmlMini_NokogiriSAX::HashBuilder
- Test
- Test::Unit
- Test::Unit::Collector
- Test::Unit::Collector::ObjectSpace
- Object
- Object::HashWithIndifferentAccess
- Object::MissingSourceFile
- ERB
- ERB::Util
- I18n
- I18n::Railtie
- LoadError
- LoadError
- Logger
- Logger::SimpleFormatter
- Array
- Base64
- Benchmark
- BigDecimal
- Class
- Date
- DateTime
- Enumerable
- FalseClass
- File
- Float
- Hash
- Integer
- Kernel
- Module
- NameError
- NilClass
- Numeric
- Process
- QualifiedConstUtils
- Range
- Regexp
- String
- Symbol
- Time
- TrueClass
- URI

No matching classes.

# Hash

### Constants

DISALLOWED_XML_TYPES

### Public Class Methods

from_trusted_xml(xml) click to toggle source

    # File lib/active_support/core_ext/hash/conversions.rb, line 101
    def from_trusted_xml(xml)
      from_xml xml, []
    end

from_xml(xml, disallowed_types = nil) click to toggle source

    # File lib/active_support/core_ext/hash/conversions.rb, line 97
    def from_xml(xml, disallowed_types = nil)
      typecast_xml_value(unrename_keys(ActiveSupport::XmlMini.parse(xml)), disallowed_types)
    end

### Public Instance Methods

assert_valid_keys(*valid_keys) click to toggle source

Validate all keys in a hash match *valid keys, raising ArgumentError on a mismatch. Note that keys are NOT treated indifferently, meaning if you use strings for keys but assert symbols as keys, this will fail.

#### Examples

    { :name => "Rob", :years => "28" }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: years"
    { :name => "Rob", :age => "28" }.assert_valid_keys("name", "age") # => raises "ArgumentError: Unknown key: name"
    { :name => "Rob", :age => "28" }.assert_valid_keys(:name, :age) # => passes, raises nothing

    # File lib/active_support/core_ext/hash/keys.rb, line 48
    def assert_valid_keys(*valid_keys)
      valid_keys.flatten!
      each_key do |k|
        raise(ArgumentError, "Unknown key: #{k}") unless valid_keys.include?(k)
      end
    end

deep_dup() click to toggle source

Returns a deep copy of hash.

    hash = { :a => { :b => 'b' } }
    dup  = hash.deep_dup
    dup[:a][:c] = 'c'

    hash[:a][:c] #=> nil
    dup[:a][:c]  #=> "c"

    # File lib/active_support/core_ext/hash/deep_dup.rb, line 10
    def deep_dup
      duplicate = self.dup
      duplicate.each_pair do |k,v|
        tv = duplicate[k]
        duplicate[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_dup : v
      end
      duplicate
    end

deep_merge(other_hash) click to toggle source

Returns a new hash with `self` and `other_hash` merged recursively.

    h1 = {:x => {:y => [4,5,6]}, :z => [7,8,9]}
    h2 = {:x => {:y => [7,8,9]}, :z => "xyz"}

    h1.deep_merge(h2) #=> { :x => {:y => [7, 8, 9]}, :z => "xyz" }
    h2.deep_merge(h1) #=> { :x => {:y => [4, 5, 6]}, :z => [7, 8, 9] }

    # File lib/active_support/core_ext/hash/deep_merge.rb, line 9
    def deep_merge(other_hash)
      dup.deep_merge!(other_hash)
    end

deep_merge!(other_hash) click to toggle source

Same as `deep_merge`, but modifies `self`.

    # File lib/active_support/core_ext/hash/deep_merge.rb, line 14
    def deep_merge!(other_hash)
      other_hash.each_pair do |k,v|
        tv = self[k]
        self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_merge(v) : v
      end
      self
    end

diff(h2) click to toggle source

Returns a hash that represents the difference between two hashes.

Examples:

    {1 => 2}.diff(1 => 2)         # => {}
    {1 => 2}.diff(1 => 3)         # => {1 => 2}
    {}.diff(1 => 2)               # => {1 => 2}
    {1 => 2, 3 => 4}.diff(1 => 2) # => {3 => 4}

    # File lib/active_support/core_ext/hash/diff.rb, line 10
    def diff(h2)
      dup.delete_if { |k, v| h2[k] == v }.merge!(h2.dup.delete_if { |k, v| has_key?(k) })
    end

encode_json(encoder) click to toggle source

    # File lib/active_support/json/encoding.rb, line 245
    def encode_json(encoder)
      # values are encoded with use_options = false, because we don't want hash representations from ActiveModel to be
      # processed once again with as_json with options, as this could cause unexpected results (i.e. missing fields);

      # on the other hand, we need to run as_json on the elements, because the model representation may contain fields
      # like Time/Date in their original (not jsonified) form, etc.

      "{#{map { |k,v| "#{encoder.encode(k.to_s)}:#{encoder.encode(v, false)}" } * ','}}"
    end

except(*keys) click to toggle source

Return a hash that includes everything but the given keys. This is useful for limiting a set of parameters to everything but a few known toggles:

    @person.update_attributes(params[:person].except(:admin))

If the receiver responds to `convert_key`, the method is called on each of the arguments. This allows `except` to play nice with hashes with indifferent access for instance:

    {:a => 1}.with_indifferent_access.except(:a)  # => {}
    {:a => 1}.with_indifferent_access.except("a") # => {}

    # File lib/active_support/core_ext/hash/except.rb, line 14
    def except(*keys)
      dup.except!(*keys)
    end

except!(*keys) click to toggle source

Replaces the hash without the given keys.

    # File lib/active_support/core_ext/hash/except.rb, line 19
    def except!(*keys)
      keys.each { |key| delete(key) }
      self
    end

extract!(*keys) click to toggle source

Removes and returns the key/value pairs matching the given keys.

    {:a => 1, :b => 2, :c => 3, :d => 4}.extract!(:a, :b) # => {:a => 1, :b => 2}

    # File lib/active_support/core_ext/hash/slice.rb, line 35
    def extract!(*keys)
      result = {}
      keys.each {|key| result[key] = delete(key) }
      result
    end

extractable_options?() click to toggle source

By default, only instances of Hash itself are extractable. Subclasses of Hash may implement this method and return true to declare themselves as extractable. If a Hash is extractable, Array#extract_options! pops it from the Array when it is the last element of the Array.

    # File lib/active_support/core_ext/array/extract_options.rb, line 7
    def extractable_options?
      instance_of?(Hash)
    end

nested_under_indifferent_access() click to toggle source

Called when object is nested under an object that receives with_indifferent_access. This method will be called on the current object by the enclosing object and is aliased to with_indifferent_access by default. Subclasses of Hash may overwrite this method to return `self` if converting to an `ActiveSupport::HashWithIndifferentAccess` would not be desirable.

    b = {:b => 1}
    {:a => b}.with_indifferent_access["a"] # calls b.nested_under_indifferent_access

Alias for: with_indifferent_access
reverse_merge(other_hash) click to toggle source

Merges the caller into `other_hash`. For example,

    options = options.reverse_merge(:size => 25, :velocity => 10)

is equivalent to

    options = {:size => 25, :velocity => 10}.merge(options)

This is particularly useful for initializing an options hash with default values.

    # File lib/active_support/core_ext/hash/reverse_merge.rb, line 12
    def reverse_merge(other_hash)
      other_hash.merge(self)
    end

reverse_merge!(other_hash) click to toggle source

Destructive `reverse_merge`.

    # File lib/active_support/core_ext/hash/reverse_merge.rb, line 17
    def reverse_merge!(other_hash)
      # right wins if there is no left
      merge!( other_hash ){|key,left,right| left }
    end

Also aliased as: reverse_update
reverse_update(other_hash) click to toggle source
Alias for: reverse_merge!
slice(*keys) click to toggle source

Slice a hash to include only the given keys. This is useful for limiting an options hash to valid keys before passing to a method:

    def search(criteria = {})
      assert_valid_keys(:mass, :velocity, :time)
    end

    search(options.slice(:mass, :velocity, :time))

If you have an array of keys you want to limit to, you should splat them:

    valid_keys = [:mass, :velocity, :time]
    search(options.slice(*valid_keys))

    # File lib/active_support/core_ext/hash/slice.rb, line 15
    def slice(*keys)
      keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
      hash = self.class.new
      keys.each { |k| hash[k] = self[k] if has_key?(k) }
      hash
    end

slice!(*keys) click to toggle source

Replaces the hash with only the given keys. Returns a hash contained the removed key/value pairs

    {:a => 1, :b => 2, :c => 3, :d => 4}.slice!(:a, :b) # => {:c => 3, :d => 4}

    # File lib/active_support/core_ext/hash/slice.rb, line 25
    def slice!(*keys)
      keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
      omit = slice(*self.keys - keys)
      hash = slice(*keys)
      replace(hash)
      omit
    end

stringify_keys() click to toggle source

Return a new hash with all keys converted to strings.

    { :name => 'Rob', :years => '28' }.stringify_keys
    #=> { "name" => "Rob", "years" => "28" }

    # File lib/active_support/core_ext/hash/keys.rb, line 6
    def stringify_keys
      dup.stringify_keys!
    end

stringify_keys!() click to toggle source

Destructively convert all keys to strings. Same as `stringify_keys`, but modifies `self`.

    # File lib/active_support/core_ext/hash/keys.rb, line 12
    def stringify_keys!
      keys.each do |key|
        self[key.to_s] = delete(key)
      end
      self
    end

symbolize_keys() click to toggle source

Return a new hash with all keys converted to symbols, as long as they respond to `to_sym`.

    { 'name' => 'Rob', 'years' => '28' }.symbolize_keys
    #=> { :name => "Rob", :years => "28" }

    # File lib/active_support/core_ext/hash/keys.rb, line 24
    def symbolize_keys
      dup.symbolize_keys!
    end

Also aliased as: to_options
symbolize_keys!() click to toggle source

Destructively convert all keys to symbols, as long as they respond to `to_sym`. Same as `symbolize_keys`, but modifies `self`.

    # File lib/active_support/core_ext/hash/keys.rb, line 30
    def symbolize_keys!
      keys.each do |key|
        self[(key.to_sym rescue key) || key] = delete(key)
      end
      self
    end

Also aliased as: to_options!
to_options() click to toggle source
Alias for: symbolize_keys
to_options!() click to toggle source
Alias for: symbolize_keys!
to_param(namespace = nil) click to toggle source

Returns a string representation of the receiver suitable for use as a URL query string:

    {:name => 'David', :nationality => 'Danish'}.to_param
    # => "name=David&nationality=Danish"

An optional namespace can be passed to enclose the param names:

    {:name => 'David', :nationality => 'Danish'}.to_param('user')
    # => "user[name]=David&user[nationality]=Danish"

The string pairs “key=value” that conform the query string are sorted lexicographically in ascending order.

This method is also aliased as `to_query`.

    # File lib/active_support/core_ext/object/to_param.rb, line 50
    def to_param(namespace = nil)
      collect do |key, value|
        value.to_query(namespace ? "#{namespace}[#{key}]" : key)
      end.sort * '&'
    end

Also aliased as: to_query
to_query(namespace = nil) click to toggle source
Alias for: to_param
to_xml(options = {}) click to toggle source

Returns a string containing an XML representation of its receiver:

    {"foo" => 1, "bar" => 2}.to_xml
    # =>
    # <?xml version="1.0" encoding="UTF-8"?>
    # <hash>
    #   <foo type="integer">1</foo>
    #   <bar type="integer">2</bar>
    # </hash>

To do so, the method loops over the pairs and builds nodes that depend on the values. Given a pair `key`, `value`:

- If `value` is a hash there’s a recursive call with `key` as `:root`.

- If `value` is an array there’s a recursive call with `key` as `:root`, and `key` singularized as `:children`.

- If `value` is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the `options` hash as first argument with `key` as `:root`, and `key` singularized as second argument. The callable can add nodes by using `options[:builder]`.

      "foo".to_xml(lambda { |options, key| options[:builder].b(key) })
      # => "<b>foo</b>"

- If `value` responds to `to_xml` the method is invoked with `key` as `:root`.

      class Foo
        def to_xml(options)
          options[:builder].bar "fooing!"
        end
      end

      {:foo => Foo.new}.to_xml(:skip_instruct => true)
      # => "<hash><bar>fooing!</bar></hash>"

- Otherwise, a node with `key` as tag is created with a string representation of `value` as text node. If `value` is `nil` an attribute “nil” set to “true” is added. Unless the option `:skip_types` exists and is true, an attribute “type” is added as well according to the following mapping:

      XML_TYPE_NAMES = {
        "Symbol"     => "symbol",
        "Fixnum"     => "integer",
        "Bignum"     => "integer",
        "BigDecimal" => "decimal",
        "Float"      => "float",
        "TrueClass"  => "boolean",
        "FalseClass" => "boolean",
        "Date"       => "date",
        "DateTime"   => "datetime",
        "Time"       => "datetime"
      }

By default the root node is “hash”, but that’s configurable via the `:root` option.

The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can configure your own builder with the `:builder` option. The method also accepts options like `:dasherize` and friends, they are forwarded to the builder.

    # File lib/active_support/core_ext/hash/conversions.rb, line 69
    def to_xml(options = {})
      require 'active_support/builder' unless defined?(Builder)

      options = options.dup
      options[:indent]  ||= 2
      options[:root]    ||= "hash"
      options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])

      builder = options[:builder]
      builder.instruct! unless options.delete(:skip_instruct)

      root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)

      builder.__send__(:method_missing, root) do
        each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options) }
        yield builder if block_given?
      end
    end

with_indifferent_access() click to toggle source

Returns an `ActiveSupport::HashWithIndifferentAccess` out of its receiver:

    {:a => 1}.with_indifferent_access["a"] # => 1

    # File lib/active_support/core_ext/hash/indifferent_access.rb, line 8
    def with_indifferent_access
      ActiveSupport::HashWithIndifferentAccess.new_from_hash_copying_default(self)
    end

Also aliased as: nested_under_indifferent_access

[Validate]

Generated with the Darkfish Rdoc Generator 2.