aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/ordered_hash.rb
diff options
context:
space:
mode:
authorFrederick Cheung <frederick.cheung@gmail.com>2008-12-09 20:36:24 +0000
committerJeremy Kemper <jeremy@bitsweat.net>2008-12-10 09:07:47 -0800
commit355f41d8aafd75d76db25cdda4736e0052b0605c (patch)
tree0dca4b27bcb61c24d38f28f34f7c6cbdc5ac4596 /activesupport/lib/active_support/ordered_hash.rb
parent014b7994ac1a829845e2882f4c852bc28bd2aa53 (diff)
downloadrails-355f41d8aafd75d76db25cdda4736e0052b0605c.tar.gz
rails-355f41d8aafd75d76db25cdda4736e0052b0605c.tar.bz2
rails-355f41d8aafd75d76db25cdda4736e0052b0605c.zip
Rework ActiveSupport::OrderedHash to make lookups faster
[#1352 state:committed] Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
Diffstat (limited to 'activesupport/lib/active_support/ordered_hash.rb')
-rw-r--r--activesupport/lib/active_support/ordered_hash.rb59
1 files changed, 23 insertions, 36 deletions
diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb
index 5de94c67e0..1ed7737017 100644
--- a/activesupport/lib/active_support/ordered_hash.rb
+++ b/activesupport/lib/active_support/ordered_hash.rb
@@ -4,62 +4,49 @@ module ActiveSupport
if RUBY_VERSION >= '1.9'
OrderedHash = ::Hash
else
- class OrderedHash < Array #:nodoc:
- def []=(key, value)
- if pair = assoc(key)
- pair.pop
- pair << value
- else
- self << [key, value]
- end
- value
+ class OrderedHash < Hash #:nodoc:
+ def initialize(*args, &block)
+ super
+ @keys = []
end
- def [](key)
- pair = assoc(key)
- pair ? pair.last : nil
+ def []=(key, value)
+ if !has_key?(key)
+ @keys << key
+ end
+ super
end
def delete(key)
- pair = assoc(key)
- pair ? array_index = index(pair) : nil
- array_index ? delete_at(array_index).last : nil
+ array_index = has_key?(key) && index(key)
+ if array_index
+ @keys.delete_at(array_index)
+ end
+ super
end
def keys
- collect { |key, value| key }
+ @keys
end
def values
- collect { |key, value| value }
+ @keys.collect { |key| self[key] }
end
def to_hash
- returning({}) do |hash|
- each { |array| hash[array[0]] = array[1] }
- end
- end
-
- def has_key?(k)
- !assoc(k).nil?
- end
-
- alias_method :key?, :has_key?
- alias_method :include?, :has_key?
- alias_method :member?, :has_key?
-
- def has_value?(v)
- any? { |key, value| value == v }
+ Hash.new(self)
end
- alias_method :value?, :has_value?
-
def each_key
- each { |key, value| yield key }
+ @keys.each { |key| yield key }
end
def each_value
- each { |key, value| yield value }
+ @keys.each { |key| yield self[key]}
+ end
+
+ def each
+ keys.each {|key| yield [key, self[key]]}
end
end
end