Class: GraphMatching::OrderedSet

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/graph_matching/ordered_set.rb

Overview

An ‘OrderedSet` acts like a `Set`, but preserves insertion order. Internally, a `Hash` is used because, as of Ruby 1.9, it preserves insertion order. The Set library happens to be built upon a Hash currently but this might change in the future.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeOrderedSet

Returns a new instance of OrderedSet.



17
18
19
# File 'lib/graph_matching/ordered_set.rb', line 17

def initialize
  @hash = {}
end

Class Method Details

.[](*args) ⇒ Object

‘.[]` returns a new ordered set containing the given objects. This mimics the signature of `Set.[]` and `Array.[]`.



13
14
15
# File 'lib/graph_matching/ordered_set.rb', line 13

def self.[](*args)
  new.merge(args)
end

Instance Method Details

#add(o) ⇒ Object Also known as: enq

‘add` `o` unless it already exists, preserving inserting order. This mimics the signature of `Set#add`. See alias `#enq`.



23
24
25
# File 'lib/graph_matching/ordered_set.rb', line 23

def add(o)
  @hash[o] = true
end

#deqObject



28
29
30
# File 'lib/graph_matching/ordered_set.rb', line 28

def deq
  @hash.keys.first.tap do |k| @hash.delete(k) end
end

#eachObject



32
33
34
# File 'lib/graph_matching/ordered_set.rb', line 32

def each
  @hash.each do |k, _v| yield k end
end

#empty?Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/graph_matching/ordered_set.rb', line 36

def empty?
  @hash.empty?
end

#merge(enum) ⇒ Object

‘merge` the elements of the given enumerable object to the set and returns self. This mimics the signature of `Set#merge`.



42
43
44
45
# File 'lib/graph_matching/ordered_set.rb', line 42

def merge(enum)
  enum.each do |e| add(e) end
  self
end

#popObject

Removes the last element and returns it, or nil if empty. This mimics ‘Array#pop`. See related `#deq`.



49
50
51
# File 'lib/graph_matching/ordered_set.rb', line 49

def pop
  @hash.keys.last.tap do |k| @hash.delete(k) end
end

#push(*args) ⇒ Object

‘push` appends the given object(s) and returns self. This mimics the signature of `Array#push`.



55
56
57
# File 'lib/graph_matching/ordered_set.rb', line 55

def push(*args)
  merge(args)
end