Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/magneto/core_ext.rb
Instance Method Summary collapse
-
#deep_merge(hash) ⇒ Object
Merges self with another hash, recursively.
- #deep_merge!(hash) ⇒ Object
-
#stringify_keys ⇒ Object
Return a new hash with all keys converted to strings.
-
#stringify_keys! ⇒ Object
Destructively convert all keys to strings.
-
#symbolize_keys ⇒ Object
Return a new hash with all keys converted to symbols, as long as they respond to
to_sym
. -
#symbolize_keys! ⇒ Object
Destructively convert all keys to symbols, as long as they respond to
to_sym
.
Instance Method Details
#deep_merge(hash) ⇒ Object
Merges self with another hash, recursively.
This code was lovingly stolen (now adapted) from some random gem: gemjack.com/gems/tartan-0.1.1/classes/Hash.html
Thanks to whoever made it.
42 43 44 |
# File 'lib/magneto/core_ext.rb', line 42 def deep_merge(hash) dup.deep_merge! hash end |
#deep_merge!(hash) ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/magneto/core_ext.rb', line 46 def deep_merge!(hash) hash.keys.each do |key| if hash[key].is_a? Hash and self[key].is_a? Hash self[key] = self[key].deep_merge(hash[key]) next end self[key] = hash[key] end self end |
#stringify_keys ⇒ Object
Return a new hash with all keys converted to strings.
7 8 9 |
# File 'lib/magneto/core_ext.rb', line 7 def stringify_keys dup.stringify_keys! end |
#stringify_keys! ⇒ Object
Destructively convert all keys to strings.
12 13 14 15 16 17 |
# File 'lib/magneto/core_ext.rb', line 12 def stringify_keys! keys.each do |key| self[key.to_s] = delete(key) end self end |
#symbolize_keys ⇒ Object
Return a new hash with all keys converted to symbols, as long as they respond to to_sym
.
21 22 23 |
# File 'lib/magneto/core_ext.rb', line 21 def symbolize_keys dup.symbolize_keys! end |
#symbolize_keys! ⇒ Object
Destructively convert all keys to symbols, as long as they respond to to_sym
.
27 28 29 30 31 32 |
# File 'lib/magneto/core_ext.rb', line 27 def symbolize_keys! keys.each do |key| self[(key.to_sym rescue key) || key] = delete(key) end self end |