Class: GraphMatching::OrderedSet
- Inherits:
-
Object
- Object
- GraphMatching::OrderedSet
- 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
-
.[](*args) ⇒ Object
‘.[]` returns a new ordered set containing the given objects.
Instance Method Summary collapse
-
#add(o) ⇒ Object
(also: #enq)
‘add` `o` unless it already exists, preserving inserting order.
- #deq ⇒ Object
- #each ⇒ Object
- #empty? ⇒ Boolean
-
#initialize ⇒ OrderedSet
constructor
A new instance of OrderedSet.
-
#merge(enum) ⇒ Object
‘merge` the elements of the given enumerable object to the set and returns self.
-
#pop ⇒ Object
Removes the last element and returns it, or nil if empty.
-
#push(*args) ⇒ Object
‘push` appends the given object(s) and returns self.
Constructor Details
#initialize ⇒ OrderedSet
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 |
#deq ⇒ Object
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 |
#each ⇒ Object
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
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 |
#pop ⇒ Object
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 |