aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/ordered_hash.rb
blob: 1ed773701735d55a21b339a17283c6d1e1d28515 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# OrderedHash is namespaced to prevent conflicts with other implementations
module ActiveSupport
  # Hash is ordered in Ruby 1.9!
  if RUBY_VERSION >= '1.9'
    OrderedHash = ::Hash
  else
    class OrderedHash < Hash #:nodoc:
      def initialize(*args, &block)
        super
        @keys = []
      end

      def []=(key, value)
        if !has_key?(key)
          @keys << key
        end
        super
      end

      def delete(key)
        array_index = has_key?(key) && index(key)
        if array_index
          @keys.delete_at(array_index)
        end
        super
      end

      def keys
        @keys
      end

      def values
        @keys.collect { |key| self[key] }
      end

      def to_hash
        Hash.new(self)
      end

      def each_key
        @keys.each { |key| yield key }
      end

      def each_value
        @keys.each { |key| yield self[key]}
      end

      def each
        keys.each {|key| yield [key, self[key]]}
      end
    end
  end
end