| Module | ActiveSupport::CoreExtensions::Hash::Keys |
| In: |
vendor/rails/activesupport/lib/active_support/core_ext/hash/keys.rb
|
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.
{ :name => "Rob", :years => "28" }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key(s): years"
{ :name => "Rob", :age => "28" }.assert_valid_keys("name", "age") # => raises "ArgumentError: Unknown key(s): name, age"
{ :name => "Rob", :age => "28" }.assert_valid_keys(:name, :age) # => passes, raises nothing
# File vendor/rails/activesupport/lib/active_support/core_ext/hash/keys.rb, line 45
45: def assert_valid_keys(*valid_keys)
46: unknown_keys = keys - [valid_keys].flatten
47: raise(ArgumentError, "Unknown key(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty?
48: end
Return a new hash with all keys converted to strings.
# File vendor/rails/activesupport/lib/active_support/core_ext/hash/keys.rb, line 6
6: def stringify_keys
7: inject({}) do |options, (key, value)|
8: options[key.to_s] = value
9: options
10: end
11: end
Destructively convert all keys to strings.
# File vendor/rails/activesupport/lib/active_support/core_ext/hash/keys.rb, line 14
14: def stringify_keys!
15: keys.each do |key|
16: self[key.to_s] = delete(key)
17: end
18: self
19: end
Return a new hash with all keys converted to symbols.
# File vendor/rails/activesupport/lib/active_support/core_ext/hash/keys.rb, line 22
22: def symbolize_keys
23: inject({}) do |options, (key, value)|
24: options[(key.to_sym rescue key) || key] = value
25: options
26: end
27: end