However, Ruby has no native
keyword argument support, so Rails has to provide some supporting features. ActiveSupport
powers this option processing with extensions on the Hash 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) and Hash_stringify_keys! (which modifies
the receiver in place) convert the hash??™s keys to strings. Hash#symbolize_keys and
Hash#symbolize_keys! convert the keys to symbols. The symbolize methods are aliased
as to_options and to_options!.
Hash
68 | Chapter 2: ActiveSupport and RailTies
h = {:a => 123, "b" => 456}
h.stringify_keys # => {"a"=>123, "b"=>456}
h.symbolize_keys # => {:a=>123, :b=>456}
??? Hash#assert_valid_keys(:key1, ...) raises an ArgumentError if the hash contains keys
not in the argument list. This is used to ensure that only valid options are provided to
a keyword-argument-based function.
??? Hash#reverse_merge and Hash#reverse_merge! (in-place) work like Hash#merge, but in
reverse order; in the case of duplicate keys, existing tuples beat those in the argument.
This can be used to provide default arguments to a function.
options = {:a => 3, :c => 5}
options.reverse_merge!(:a => 1, :b => 4)
options # => {:a=>3, :b=>4, :c=>5}
??? Hash#slice returns a new hash with only the keys specified.
Pages:
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112