Hash
Hash | 67
Hash
Conversions core_ext/hash/conversions.rb
Many methods are provided to convert back and forth between hashes and XML represen-
tation. These are useful for round-tripping a hash to and from XML for web services.
- Hash#to_xml converts a single-level hash to XML:
{:a => "One", :b => "Two", :int => 1, :opt => false}.to_xml
yields:
<?xml version="1.0" encoding="UTF-8"?>
One
Two
1
false
- Hash.from_xmlcreates a hash from the provided XML document. Note that the root
element is included in the hash.
xml = <<EOXML
<?xml version="1.0" encoding="UTF-8"?>
One
Two
EOXML
Hash.from_xml(xml)["hash"] # => {"a"=>"One", "b"=>"Two"}
Option processing core_ext/hash/diff.rb,core_ext/hash/keys.rb,core_ext/hash/reverse_merge.rb,
core_ext/hash/slice.rb,core_ext/hash/except.rb
Rails uses hashes to provide keyword arguments to many methods. This is mostly due to a
bit of syntactic sugar on Ruby’s part; if a hash is passed as a function’s last argument, the
brackets can be omitted, resembling keyword arguments. However, Ruby has no native
keyword argument support, so Rails has to provide some supporting features. ActiveSupport
powers this option processing with extensions on theHash class.
- Hash#diff(other)collects a hash with key/value pairs that are in one hash but not
another.
a = {:a => :b, :c => :d}
b = {:e => :f, :c => :d}
a.diff(b) # => {:e=>:f, :a=>:b} - Hash#stringify_keys(which returns a copy) andHash_stringify_keys!(which modi-
fies the receiver in place) convert the hash’s keys to strings.Hash#symbolize_keysand
Hash#symbolize_keys!convert the keys to symbols. The symbolize methods are aliased
asto_options andto_options!.