Class Hash
In: lib/active_support/json/encoding.rb
lib/active_support/core_ext/object/to_param.rb
lib/active_support/core_ext/object/blank.rb
lib/active_support/core_ext/object/to_query.rb
lib/active_support/core_ext/hash/deep_merge.rb
lib/active_support/core_ext/hash/indifferent_access.rb
lib/active_support/core_ext/hash/conversions.rb
lib/active_support/core_ext/hash/reverse_merge.rb
lib/active_support/core_ext/hash/keys.rb
lib/active_support/core_ext/hash/deep_dup.rb
lib/active_support/core_ext/hash/except.rb
lib/active_support/core_ext/hash/diff.rb
lib/active_support/core_ext/hash/slice.rb
lib/active_support/core_ext/array/extract_options.rb
Parent: Object

Methods

External Aliases

empty? -> blank?
  A hash is blank if it‘s empty:
  {}.blank?                # => true
  {:key => 'value'}.blank? # => false

Public Class methods

Public Instance methods

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

Returns a deep copy of hash.

Returns a new hash with self and other_hash merged recursively.

Returns a new hash with self and other_hash merged recursively. Modifies the receiver in place.

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}

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") # => {}

Replaces the hash without the given keys.

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}

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.

nested_under_indifferent_access()

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.

reverse_update(other_hash)

Alias for reverse_merge!

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))

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}

Return a new hash with all keys converted to strings.

Destructively convert all keys to strings.

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

Destructively convert all keys to symbols, as long as they respond to to_sym.

to_options()

Alias for symbolize_keys

to_options!()

Alias for symbolize_keys!

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.

to_query(namespace = nil)

Alias for to_param

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.

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

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

[Validate]