From c0262827cacc1baf16668af65c35a09138166394 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim=20and=20Mikel=20Lindsaar?= Date: Sun, 24 Jan 2010 23:40:45 +0100 Subject: Speed up some Hash core extensions. --- .../lib/active_support/core_ext/hash/deep_merge.rb | 13 ++++++------- activesupport/lib/active_support/core_ext/hash/keys.rb | 15 ++++++--------- 2 files changed, 12 insertions(+), 16 deletions(-) (limited to 'activesupport/lib/active_support/core_ext') diff --git a/activesupport/lib/active_support/core_ext/hash/deep_merge.rb b/activesupport/lib/active_support/core_ext/hash/deep_merge.rb index 24d0a2a481..af771c86ff 100644 --- a/activesupport/lib/active_support/core_ext/hash/deep_merge.rb +++ b/activesupport/lib/active_support/core_ext/hash/deep_merge.rb @@ -1,17 +1,16 @@ class Hash # Returns a new hash with +self+ and +other_hash+ merged recursively. def deep_merge(other_hash) - target = dup - other_hash.each_pair do |k,v| - tv = target[k] - target[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_merge(v) : v - end - target + dup.deep_merge!(other_hash) end # Returns a new hash with +self+ and +other_hash+ merged recursively. # Modifies the receiver in place. def deep_merge!(other_hash) - replace(deep_merge(other_hash)) + other_hash.each_pair do |k,v| + tv = self[k] + self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_merge(v) : v + end + self end end diff --git a/activesupport/lib/active_support/core_ext/hash/keys.rb b/activesupport/lib/active_support/core_ext/hash/keys.rb index ecd63293b4..045a6944fa 100644 --- a/activesupport/lib/active_support/core_ext/hash/keys.rb +++ b/activesupport/lib/active_support/core_ext/hash/keys.rb @@ -1,10 +1,7 @@ class Hash # Return a new hash with all keys converted to strings. def stringify_keys - inject({}) do |options, (key, value)| - options[key.to_s] = value - options - end + dup.stringify_keys! end # Destructively convert all keys to strings. @@ -18,16 +15,16 @@ class Hash # Return a new hash with all keys converted to symbols, as long as # they respond to +to_sym+. def symbolize_keys - inject({}) do |options, (key, value)| - options[(key.to_sym rescue key) || key] = value - options - end + dup.symbolize_keys! end # Destructively convert all keys to symbols, as long as they respond # to +to_sym+. def symbolize_keys! - self.replace(self.symbolize_keys) + keys.each do |key| + self[(key.to_sym rescue key) || key] = delete(key) + end + self end alias_method :to_options, :symbolize_keys -- cgit v1.2.3