Class: Thor::CoreExt::OrderedHash

Inherits:
Hash
  • Object
show all
Includes:
Enumerable
Defined in:
lib/thor/core_ext/ordered_hash.rb,
lib/thor/core_ext/ordered_hash.rb

Defined Under Namespace

Classes: Node

Instance Method Summary (collapse)

Constructor Details

- (OrderedHash) initialize



18
19
20
# File 'lib/thor/core_ext/ordered_hash.rb', line 18

def initialize
  @hash = {}
end

Instance Method Details

- (Object) [](key)



22
23
24
# File 'lib/thor/core_ext/ordered_hash.rb', line 22

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

- (Object) []=(key, value)



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/thor/core_ext/ordered_hash.rb', line 26

def []=(key, value)
  if node = @hash[key]
    node.value = value
  else
    node = Node.new(key, value)

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

  @hash[key] = node
  value
end

- (Object) delete(key)



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/thor/core_ext/ordered_hash.rb', line 45

def delete(key)
  if node = @hash[key]
    prev_node = node.prev
    next_node = node.next

    next_node.prev = prev_node if next_node
    prev_node.next = next_node if prev_node

    @first = next_node if @first == node
    @last = prev_node  if @last  == node

    value = node.value
  end

  @hash.delete(key)
  value
end

- (Object) each {|[@first.key, @first.value]| ... }

Yields:

  • ([@first.key, @first.value])


71
72
73
74
75
76
77
# File 'lib/thor/core_ext/ordered_hash.rb', line 71

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

- (Boolean) empty?



93
94
95
# File 'lib/thor/core_ext/ordered_hash.rb', line 93

def empty?
  @hash.empty?
end

- (Object) keys



63
64
65
# File 'lib/thor/core_ext/ordered_hash.rb', line 63

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

- (Object) merge(other)



79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/thor/core_ext/ordered_hash.rb', line 79

def merge(other)
  hash = self.class.new

  self.each do |key, value|
    hash[key] = value
  end

  other.each do |key, value|
    hash[key] = value
  end

  hash
end

- (Object) values



67
68
69
# File 'lib/thor/core_ext/ordered_hash.rb', line 67

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