Class: Hash
Class Method Summary
- .from_trusted_xml(xml)
-
.from_xml(xml, disallowed_types = nil)
Returns a
Hash
containing a collection of pairs when the key is the node name and the value is its content.
Instance Attribute Summary
-
#extractable_options? ⇒ Boolean
readonly
By default, only instances of
Hash
itself are extractable.
Instance Method Summary
-
#assert_valid_keys(*valid_keys)
Validates all keys in a hash match
*valid_keys
, raisingArgumentError
on a mismatch. -
#blank? ⇒ true, false
A hash is blank if it’s empty:
-
#compact_blank!
Removes all blank values from the
Hash
in place and returns self. -
#deep_dup
Returns a deep copy of hash.
-
#deep_merge(other_hash, &block)
Returns a new hash with
self
andother_hash
merged recursively. -
#deep_merge!(other_hash, &block)
Same as #deep_merge, but modifies
self
. -
#deep_stringify_keys
Returns a new hash with all keys converted to strings.
-
#deep_stringify_keys!
Destructively converts all keys to strings.
-
#deep_symbolize_keys
Returns a new hash with all keys converted to symbols, as long as they respond to
to_sym
. -
#deep_symbolize_keys!
Destructively converts all keys to symbols, as long as they respond to
to_sym
. -
#deep_transform_keys(&block)
Returns a new hash with all keys converted by the block operation.
-
#deep_transform_keys!(&block)
Destructively converts all keys by using the block operation.
-
#deep_transform_values(&block)
Returns a new hash with all values converted by the block operation.
-
#deep_transform_values!(&block)
Destructively converts all values by using the block operation.
-
#except(*keys)
Returns a hash that includes everything except given keys.
-
#except!(*keys)
Removes the given keys from hash and returns it.
-
#extract!(*keys)
Removes and returns the key/value pairs matching the given keys.
-
#nested_under_indifferent_access
Alias for #with_indifferent_access.
-
#reverse_merge(other_hash)
(also: #with_defaults)
Merges the caller into
other_hash
. -
#reverse_merge!(other_hash)
(also: #reverse_update, #with_defaults!)
Destructive #reverse_merge.
-
#reverse_update(other_hash)
Alias for #reverse_merge!.
-
#slice!(*keys)
Replaces the hash with only the given keys.
-
#stringify_keys
Returns a new hash with all keys converted to strings.
-
#stringify_keys!
Destructively converts all keys to strings.
-
#symbolize_keys
(also: #to_options)
Returns a new hash with all keys converted to symbols, as long as they respond to
to_sym
. -
#symbolize_keys!
(also: #to_options!)
Destructively converts all keys to symbols, as long as they respond to
to_sym
. -
#to_options
Alias for #symbolize_keys.
-
#to_options!
Alias for #symbolize_keys!.
-
#to_param(namespace = nil)
Alias for #to_query.
-
#to_query(namespace = nil)
(also: #to_param)
Returns a string representation of the receiver suitable for use as a URL query string:
-
#to_xml(options = {})
Returns a string containing an XML representation of its receiver:
-
#with_defaults(other_hash)
Alias for #reverse_merge.
-
#with_defaults!(other_hash)
Alias for #reverse_merge!.
-
#with_indifferent_access
(also: #nested_under_indifferent_access)
Returns an
::ActiveSupport::HashWithIndifferentAccess
out of its receiver:
Class Method Details
.from_trusted_xml(xml)
[ GitHub ]# File 'activesupport/lib/active_support/core_ext/hash/conversions.rb', line 134
def from_trusted_xml(xml) from_xml xml, [] end
.from_xml(xml, disallowed_types = nil)
Returns a Hash
containing a collection of pairs when the key is the node name and the value is its content
xml = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<hash>
<foo type="integer">1</foo>
<bar type="integer">2</bar>
</hash>
XML
hash = Hash.from_xml(xml)
# => {"hash"=>{"foo"=>1, "bar"=>2}}
DisallowedType
is raised if the XML contains attributes with type="yaml"
or type="symbol"
. Use .from_trusted_xml to parse this XML.
Custom disallowed_types
can also be passed in the form of an array.
xml = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<hash>
<foo type="integer">1</foo>
<bar type="string">"David"</bar>
</hash>
XML
hash = Hash.from_xml(xml, ['integer'])
# => ActiveSupport::XMLConverter::DisallowedType: Disallowed type attribute: "integer"
Note that passing custom disallowed types will override the default types, which are ::Symbol
and YAML.
# File 'activesupport/lib/active_support/core_ext/hash/conversions.rb', line 129
def from_xml(xml, disallowed_types = nil) ActiveSupport::XMLConverter.new(xml, disallowed_types).to_h end
Instance Attribute Details
#extractable_options? ⇒ Boolean
(readonly)
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 'activesupport/lib/active_support/core_ext/array/extract_options.rb', line 9
def instance_of?(Hash) end
Instance Method Details
#assert_valid_keys(*valid_keys)
Validates all keys in a hash match *valid_keys
, raising ArgumentError
on a mismatch.
Note that keys are treated differently than HashWithIndifferentAccess, meaning that string and symbol keys will not match.
{ name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: :years. Valid keys are: :name, :age"
{ name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: :name. Valid keys are: 'name', 'age'"
{ name: 'Rob', age: '28' }.assert_valid_keys(:name, :age) # => passes, raises nothing
# File 'activesupport/lib/active_support/core_ext/hash/keys.rb', line 48
def assert_valid_keys(*valid_keys) valid_keys.flatten! each_key do |k| unless valid_keys.include?(k) raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{valid_keys.map(&:inspect).join(', ')}") end end end
#blank? ⇒ true
, false
A hash is blank if it’s empty:
{}.blank? # => true
{ key: 'value' }.blank? # => false
# File 'activesupport/lib/active_support/core_ext/object/blank.rb', line 100
alias_method :blank?, :empty?
#compact_blank!
Removes all blank values from the Hash
in place and returns self. Uses Object#blank? for determining if a value is blank.
h = { a: "", b: 1, c: nil, d: [], e: false, f: true }
h.compact_blank!
# => { b: 1, f: true }
# File 'activesupport/lib/active_support/core_ext/enumerable.rb', line 208
def compact_blank! # use delete_if rather than reject! because it always returns self even if nothing changed delete_if { |_k, v| v.blank? } end
#deep_dup
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"
#deep_merge(other_hash, &block)
Returns a new hash with self
and other_hash
merged recursively.
h1 = { a: true, b: { c: [1, 2, 3] } }
h2 = { a: false, b: { x: [3, 4, 5] } }
h1.deep_merge(h2) # => { a: false, b: { c: [1, 2, 3], x: [3, 4, 5] } }
Like with Hash#merge
in the standard library, a block can be provided to merge values:
h1 = { a: 100, b: 200, c: { c1: 100 } }
h2 = { b: 250, c: { c1: 200 } }
h1.deep_merge(h2) { |key, this_val, other_val| this_val + other_val }
# => { a: 100, b: 450, c: { c1: 300 } }
# File 'activesupport/lib/active_support/core_ext/hash/deep_merge.rb', line 18
def deep_merge(other_hash, &block) dup.deep_merge!(other_hash, &block) end
#deep_merge!(other_hash, &block)
Same as #deep_merge, but modifies self
.
# File 'activesupport/lib/active_support/core_ext/hash/deep_merge.rb', line 23
def deep_merge!(other_hash, &block) merge!(other_hash) do |key, this_val, other_val| if this_val.is_a?(Hash) && other_val.is_a?(Hash) this_val.deep_merge(other_val, &block) elsif block_given? block.call(key, this_val, other_val) else other_val end end end
#deep_stringify_keys
Returns a new hash with all keys converted to strings. This includes the keys from the root hash and from all nested hashes and arrays.
hash = { person: { name: 'Rob', age: '28' } }
hash.deep_stringify_keys
# => {"person"=>{"name"=>"Rob", "age"=>"28"}}
# File 'activesupport/lib/active_support/core_ext/hash/keys.rb', line 84
def deep_stringify_keys deep_transform_keys(&:to_s) end
#deep_stringify_keys!
Destructively converts all keys to strings. This includes the keys from the root hash and from all nested hashes and arrays.
# File 'activesupport/lib/active_support/core_ext/hash/keys.rb', line 91
def deep_stringify_keys! deep_transform_keys!(&:to_s) end
#deep_symbolize_keys
Returns a new hash with all keys converted to symbols, as long as they respond to to_sym
. This includes the keys from the root hash and from all nested hashes and arrays.
hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } }
hash.deep_symbolize_keys
# => {:person=>{:name=>"Rob", :age=>"28"}}
# File 'activesupport/lib/active_support/core_ext/hash/keys.rb', line 103
def deep_symbolize_keys deep_transform_keys { |key| key.to_sym rescue key } end
#deep_symbolize_keys!
Destructively converts all keys to symbols, as long as they respond to to_sym
. This includes the keys from the root hash and from all nested hashes and arrays.
# File 'activesupport/lib/active_support/core_ext/hash/keys.rb', line 110
def deep_symbolize_keys! deep_transform_keys! { |key| key.to_sym rescue key } end
#deep_transform_keys(&block)
Returns a new hash with all keys converted by the block operation. This includes the keys from the root hash and from all nested hashes and arrays.
hash = { person: { name: 'Rob', age: '28' } }
hash.deep_transform_keys{ |key| key.to_s.upcase }
# => {"PERSON"=>{"NAME"=>"Rob", "AGE"=>"28"}}
# File 'activesupport/lib/active_support/core_ext/hash/keys.rb', line 65
def deep_transform_keys(&block) _deep_transform_keys_in_object(self, &block) end
#deep_transform_keys!(&block)
Destructively converts all keys by using the block operation. This includes the keys from the root hash and from all nested hashes and arrays.
# File 'activesupport/lib/active_support/core_ext/hash/keys.rb', line 72
def deep_transform_keys!(&block) _deep_transform_keys_in_object!(self, &block) end
#deep_transform_values(&block)
Returns a new hash with all values converted by the block operation. This includes the values from the root hash and from all nested hashes and arrays.
hash = { person: { name: 'Rob', age: '28' } }
hash.deep_transform_values{ |value| value.to_s.upcase }
# => {person: {name: "ROB", age: "28"}}
# File 'activesupport/lib/active_support/core_ext/hash/deep_transform_values.rb', line 12
def deep_transform_values(&block) _deep_transform_values_in_object(self, &block) end
#deep_transform_values!(&block)
Destructively converts all values by using the block operation. This includes the values from the root hash and from all nested hashes and arrays.
# File 'activesupport/lib/active_support/core_ext/hash/deep_transform_values.rb', line 19
def deep_transform_values!(&block) _deep_transform_values_in_object!(self, &block) end
#except(*keys)
Returns a hash that includes everything except given keys.
hash = { a: true, b: false, c: nil }
hash.except(:c) # => { a: true, b: false }
hash.except(:a, :b) # => { c: nil }
hash # => { a: true, b: false, c: nil }
This is useful for limiting a set of parameters to everything but a few known toggles:
@person.update(params[:person].except(:admin))
# File 'activesupport/lib/active_support/core_ext/hash/except.rb', line 12
def except(*keys) slice(*self.keys - keys) end
#except!(*keys)
Removes the given keys from hash and returns it.
hash = { a: true, b: false, c: nil }
hash.except!(:c) # => { a: true, b: false }
hash # => { a: true, b: false }
# File 'activesupport/lib/active_support/core_ext/hash/except.rb', line 20
def except!(*keys) keys.each { |key| delete(key) } self end
#extract!(*keys)
Removes and returns the key/value pairs matching the given keys.
hash = { a: 1, b: 2, c: 3, d: 4 }
hash.extract!(:a, :b) # => {:a=>1, :b=>2}
hash # => {:c=>3, :d=>4}
# File 'activesupport/lib/active_support/core_ext/hash/slice.rb', line 24
def extract!(*keys) keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) } end
#nested_under_indifferent_access
Alias for #with_indifferent_access.
# File 'activesupport/lib/active_support/core_ext/hash/indifferent_access.rb', line 23
alias nested_under_indifferent_access with_indifferent_access
#reverse_merge(other_hash) Also known as: #with_defaults
Merges the caller into other_hash
. For example,
= .reverse_merge(size: 25, velocity: 10)
is equivalent to
= { size: 25, velocity: 10 }.merge( )
This is particularly useful for initializing an options hash with default values.
# File 'activesupport/lib/active_support/core_ext/hash/reverse_merge.rb', line 14
def reverse_merge(other_hash) other_hash.merge(self) end
#reverse_merge!(other_hash) Also known as: #reverse_update, #with_defaults!
Destructive #reverse_merge.
# File 'activesupport/lib/active_support/core_ext/hash/reverse_merge.rb', line 20
def reverse_merge!(other_hash) replace(reverse_merge(other_hash)) end
#reverse_update(other_hash)
Alias for #reverse_merge!.
# File 'activesupport/lib/active_support/core_ext/hash/reverse_merge.rb', line 23
alias_method :reverse_update, :reverse_merge!
#slice!(*keys)
Replaces the hash with only the given keys. Returns a hash containing the removed key/value pairs.
hash = { a: 1, b: 2, c: 3, d: 4 }
hash.slice!(:a, :b) # => {:c=>3, :d=>4}
hash # => {:a=>1, :b=>2}
# File 'activesupport/lib/active_support/core_ext/hash/slice.rb', line 10
def slice!(*keys) omit = slice(*self.keys - keys) hash = slice(*keys) hash.default = default hash.default_proc = default_proc if default_proc replace(hash) omit end
#stringify_keys
Returns a new hash with all keys converted to strings.
hash = { name: 'Rob', age: '28' }
hash.stringify_keys
# => {"name"=>"Rob", "age"=>"28"}
# File 'activesupport/lib/active_support/core_ext/hash/keys.rb', line 10
def stringify_keys transform_keys(&:to_s) end
#stringify_keys!
Destructively converts all keys to strings. Same as #stringify_keys, but modifies self
.
# File 'activesupport/lib/active_support/core_ext/hash/keys.rb', line 16
def stringify_keys! transform_keys!(&:to_s) end
#symbolize_keys Also known as: #to_options
Returns a new hash with all keys converted to symbols, as long as they respond to to_sym
.
hash = { 'name' => 'Rob', 'age' => '28' }
hash.symbolize_keys
# => {:name=>"Rob", :age=>"28"}
# File 'activesupport/lib/active_support/core_ext/hash/keys.rb', line 27
def symbolize_keys transform_keys { |key| key.to_sym rescue key } end
#symbolize_keys! Also known as: #to_options!
Destructively converts all keys to symbols, as long as they respond to to_sym
. Same as #symbolize_keys, but modifies self
.
# File 'activesupport/lib/active_support/core_ext/hash/keys.rb', line 34
def symbolize_keys! transform_keys! { |key| key.to_sym rescue key } end
#to_options
Alias for #symbolize_keys.
# File 'activesupport/lib/active_support/core_ext/hash/keys.rb', line 30
alias_method :, :symbolize_keys
#to_options!
Alias for #symbolize_keys!.
# File 'activesupport/lib/active_support/core_ext/hash/keys.rb', line 37
alias_method :, :symbolize_keys!
#to_param(namespace = nil)
Alias for #to_query.
# File 'activesupport/lib/active_support/core_ext/object/to_query.rb', line 88
alias_method :to_param, :to_query
#to_query(namespace = nil) Also known as: #to_param
Returns a string representation of the receiver suitable for use as a URL query string:
{name: 'David', nationality: 'Danish'}.to_query
# => "name=David&nationality=Danish"
An optional namespace can be passed to enclose key names:
{name: 'David', nationality: 'Danish'}.to_query('user')
# => "user%5Bname%5D=David&user%5Bnationality%5D=Danish"
The string pairs “key=value” that conform the query string are sorted lexicographically in ascending order.
This method is also aliased as #to_param.
# File 'activesupport/lib/active_support/core_ext/object/to_query.rb', line 77
def to_query(namespace = nil) query = collect do |key, value| unless (value.is_a?(Hash) || value.is_a?(Array)) && value.empty? value.to_query(namespace ? "#{namespace}[#{key}]" : key) end end.compact query.sort! unless namespace.to_s.include?("[]") query.join("&") end
#to_xml(options = {})
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 withkey
as:root
. -
If
value
is an array there’s a recursive call withkey
as:root
, andkey
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 theoptions
hash as first argument withkey
as:root
, andkey
singularized as second argument. The callable can add nodes by usingoptions[:builder]
.{foo: lambda { |, key| [:builder].b(key) }}.to_xml # => "<b>foo</b>"
-
If
value
responds toto_xml
the method is invoked withkey
as:root
.class Foo def to_xml( ) [:builder]. '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 ofvalue
as text node. Ifvalue
isnil
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", "Integer" => "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 'activesupport/lib/active_support/core_ext/hash/conversions.rb', line 75
def to_xml( = {}) require "active_support/builder" unless defined?(Builder::XmlMarkup) = .dup [:indent] ||= 2 [:root] ||= "hash" [:builder] ||= Builder::XmlMarkup.new(indent: [:indent]) builder = [:builder] builder.instruct! unless .delete(:skip_instruct) root = ActiveSupport::XmlMini.rename_key( [:root].to_s, ) builder.tag!(root) do each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, ) } yield builder if block_given? end end
#with_defaults(other_hash)
Alias for #reverse_merge.
# File 'activesupport/lib/active_support/core_ext/hash/reverse_merge.rb', line 17
alias_method :with_defaults, :reverse_merge
#with_defaults!(other_hash)
Alias for #reverse_merge!.
# File 'activesupport/lib/active_support/core_ext/hash/reverse_merge.rb', line 24
alias_method :with_defaults!, :reverse_merge!
#with_indifferent_access Also known as: #nested_under_indifferent_access
Returns an ::ActiveSupport::HashWithIndifferentAccess
out of its receiver:
{ a: 1 }.with_indifferent_access['a'] # => 1
# File 'activesupport/lib/active_support/core_ext/hash/indifferent_access.rb', line 9
def with_indifferent_access ActiveSupport::HashWithIndifferentAccess.new(self) end