Permalink
Browse files

Backporting some docs on core_ext/hash

  • Loading branch information...
1 parent e9051e2 commit b2f73c40b8a995ed685fc76f2df724b15ead16b6 Francesco Rodriguez committed May 15, 2012
@@ -1,5 +1,12 @@
class Hash
# Returns a deep copy of hash.
+ #
+ # hash = { :a => { :b => 'b' } }
+ # dup = hash.deep_dup
+ # dup[:a][:c] = 'c'
+ #
+ # hash[:a][:c] #=> nil
+ # dup[:a][:c] #=> "c"
def deep_dup
duplicate = self.dup
duplicate.each_pair do |k,v|
@@ -1,11 +1,16 @@
class Hash
# Returns a new hash with +self+ and +other_hash+ merged recursively.
+ #
+ # h1 = {:x => {:y => [4,5,6]}, :z => [7,8,9]}
+ # h2 = {:x => {:y => [7,8,9]}, :z => "xyz"}
+ #
+ # h1.deep_merge(h2) #=> { :x => {:y => [7, 8, 9]}, :z => "xyz" }
+ # h2.deep_merge(h1) #=> { :x => {:y => [4, 5, 6]}, :z => [7, 8, 9] }
def deep_merge(other_hash)
dup.deep_merge!(other_hash)
end
- # Returns a new hash with +self+ and +other_hash+ merged recursively.
- # Modifies the receiver in place.
+ # Same as +deep_merge+, but modifies +self+.
def deep_merge!(other_hash)
other_hash.each_pair do |k,v|
tv = self[k]
@@ -1,10 +1,14 @@
class Hash
# Return a new hash with all keys converted to strings.
+ #
+ # { :name => 'Rob', :years => '28' }.stringify_keys
+ # #=> { "name" => "Rob", "years" => "28" }
def stringify_keys
dup.stringify_keys!
end
- # Destructively convert all keys to strings.
+ # Destructively convert all keys to strings. Same as
+ # +stringify_keys+, but modifies +self+.
def stringify_keys!
keys.each do |key|
self[key.to_s] = delete(key)
@@ -14,12 +18,15 @@ def stringify_keys!
# Return a new hash with all keys converted to symbols, as long as
# they respond to +to_sym+.
+ #
+ # { 'name' => 'Rob', 'years' => '28' }.symbolize_keys
+ # #=> { :name => "Rob", :years => "28" }
def symbolize_keys
dup.symbolize_keys!
end
# Destructively convert all keys to symbols, as long as they respond
- # to +to_sym+.
+ # to +to_sym+. Same as +symbolize_keys+, but modifies +self+.
def symbolize_keys!
keys.each do |key|
self[(key.to_sym rescue key) || key] = delete(key)

0 comments on commit b2f73c4

Please sign in to comment.