Hash (original) (raw)

Methods

A

D

E

F

N

R

S

T

W

Class Public methods

from_xml(xml)

Source: show

def from_xml(xml) typecast_xml_value(unrename_keys(ActiveSupport::XmlMini.parse(xml))) end

Instance Public methods

assert_valid_keys(*valid_keys)

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) { :name => "Rob", :age => "28" }.assert_valid_keys("name", "age") { :name => "Rob", :age => "28" }.assert_valid_keys(:name, :age)

Source: show

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

Returns a deep copy of hash.

Source: show

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)

Returns a new hash with self and other_hashmerged recursively.

Source: show

def deep_merge(other_hash) dup.deep_merge!(other_hash) end

deep_merge!(other_hash)

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

Source: show

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)

Returns a hash that represents the difference between two hashes.

Examples:

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

Source: show

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)

Source: show

def encode_json(encoder)

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

except(*keys)

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

Source: show

def except(*keys) dup.except!(*keys) end

except!(*keys)

Replaces the hash without the given keys.

Source: show

def except!(*keys) keys.each { |key| delete(key) } self end

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

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

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

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_accessby 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"]

reverse_merge(other_hash)

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.

Source: show

def reverse_merge(other_hash) other_hash.merge(self) end

reverse_merge!(other_hash)

Destructive reverse_merge.

Source: show

def reverse_merge!(other_hash)

merge!( other_hash ){|key,left,right| left } end

reverse_update(other_hash)

slice(*keys)

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

Source: show

def slice(*keys) keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key) hash = self.class.new keys.each { |k| hash[k] = self[k] if has_key?(k) } hash end

slice!(*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)

Source: show

def slice!(*keys) keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key) omit = slice(*self.keys - keys) hash = slice(*keys) replace(hash) omit end

stringify_keys()

Return a new hash with all keys converted to strings.

Source: show

def stringify_keys dup.stringify_keys! end

stringify_keys!()

Destructively convert all keys to strings.

Source: show

def stringify_keys! keys.each do |key| self[key.to_s] = delete(key) end self end

symbolize_keys()

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

Source: show

def symbolize_keys dup.symbolize_keys! end

symbolize_keys!()

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

Source: show

def symbolize_keys! keys.each do |key| self[(key.to_sym rescue key) || key] = delete(key) end self end

to_param(namespace = nil)

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

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

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

{:name => 'David', :nationality => 'Danish'}.to_param('user')

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

This method is also aliased as to_query.

Source: show

def to_param(namespace = nil) collect do |key, value| value.to_query(namespace ? "#{namespace}[#{key}]" : key) end.sort * '&' end

to_query(namespace = nil)

to_xml(options = {})

Returns a string containing an XML representation of its receiver:

{"foo" => 1, "bar" => 2}.to_xml

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

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

The default XML builder is a fresh instance ofBuilder::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.

Source: show

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

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

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

Source: show

def with_indifferent_access ActiveSupport::HashWithIndifferentAccess.new_from_hash_copying_default(self) end