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 symbol as keys, this will fail. examples:
{ :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): years, name" { :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 47 47: def assert_valid_keys(*valid_keys) 48: unknown_keys = keys - [valid_keys].flatten 49: raise(ArgumentError, "Unknown key(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty? 50: 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: unless key.class.to_s == "String" # weird hack to make the tests run when string_ext_test.rb is also running 17: self[key.to_s] = self[key] 18: delete(key) 19: end 20: end 21: self 22: end
Return a new hash with all keys converted to symbols.
# File vendor/rails/activesupport/lib/active_support/core_ext/hash/keys.rb, line 25 25: def symbolize_keys 26: inject({}) do |options, (key, value)| 27: options[key.to_sym || key] = value 28: options 29: end 30: end