Sha256: be668f6214555522f2eb249b961435a6561be3f5e09362d7dd8ca5a29e0c935c

Contents?: true

Size: 1.28 KB

Versions: 32

Compression:

Stored size: 1.28 KB

Contents

class Thor
  # This class is based on the Ruby 1.9 ordered hashes.
  # It keeps the semantics and most of the efficiency of normal hashes
  # while also keeping track of the order in which elements were set.
  class OrderedHash
    Node = Struct.new(:key, :value, :next, :prev)
    include Enumerable

    def initialize
      @hash = {}
    end

    def initialize_copy(other)
      @hash = other.instance_variable_get('@hash').clone
    end

    def [](key)
      @hash[key] && @hash[key].value
    end

    def []=(key, value)
      node = Node.new(key, value)

      if old = @hash[key]
        if old.prev
          old.prev.next = old.next
        else # old is @first and @last
          @first = @last = nil
        end
      end

      if @first.nil?
        @first = @last = node
      else
        node.prev = @last
        @last.next = node
        @last = node
      end

      @hash[key] = node
      value
    end

    def each
      return unless @first
      yield [@first.key, @first.value]
      node = @first
      yield [node.key, node.value] while node = node.next
      self
    end

    def values
      self.map { |k, v| v }
    end

    def +(other)
      new = clone
      other.each do |key, value|
        new[key] = value unless self[key]
      end
      new
    end
  end
end

Version data entries

32 entries across 32 versions & 7 rubygems

Version Path
jherdman-thor-0.9.5 lib/thor/ordered_hash.rb
mislav-thor-0.9.10 lib/thor/ordered_hash.rb
mislav-thor-0.9.5 lib/thor/ordered_hash.rb
sproutit-sproutcore-1.0.0.20090408130025 lib/thor/lib/thor/ordered_hash.rb
sproutit-sproutcore-1.0.0.20090416161445 lib/thor/lib/thor/ordered_hash.rb
sproutit-sproutcore-1.0.0.20090720093355 lib/thor/lib/thor/ordered_hash.rb
sproutit-sproutcore-1.0.0.20090720202429 lib/thor/lib/thor/ordered_hash.rb
sproutit-sproutcore-1.0.0.20090721125122 lib/thor/lib/thor/ordered_hash.rb
sproutit-sproutcore-1.0.126 lib/thor/lib/thor/ordered_hash.rb
sproutit-sproutcore-1.0.20090721145251 lib/thor/lib/thor/ordered_hash.rb
sproutit-sproutcore-1.0.20090721145280 lib/thor/lib/thor/ordered_hash.rb
sproutit-sproutcore-1.0.20090721145281 lib/thor/lib/thor/ordered_hash.rb
sproutit-sproutcore-1.0.20090721145282 lib/thor/lib/thor/ordered_hash.rb
sproutit-sproutcore-1.0.20090721145285 lib/thor/lib/thor/ordered_hash.rb
sproutit-sproutcore-1.0.203 lib/thor/lib/thor/ordered_hash.rb
wycats-thor-0.9.2 lib/thor/ordered_hash.rb
wycats-thor-0.9.5 lib/thor/ordered_hash.rb
wycats-thor-0.9.6 lib/thor/ordered_hash.rb
wycats-thor-0.9.7 lib/thor/ordered_hash.rb
wycats-thor-0.9.8 lib/thor/ordered_hash.rb