Methods
- assert_valid_keys
- stringify_keys
- stringify_keys!
- symbolize_keys
- symbolize_keys!
- to_options
- to_options!
Public Instance methods
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.
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): name, age" { :name => "Rob", :age => "28" }.assert_valid_keys(:name, :age) # => passes, raises nothing
[ show source ]
# File 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.
[ show source ]
# File 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.
[ show source ]
# File 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.
This method is also aliased as
to_options
[ show source ]
# File 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
Destructively convert all keys to symbols.
This method is also aliased as
to_options!
[ show source ]
# File activesupport/lib/active_support/core_ext/hash/keys.rb, line 30 30: def symbolize_keys! 31: self.replace(self.symbolize_keys) 32: end
Alias for symbolize_keys
Alias for symbolize_keys!