| Class | Set |
| In: |
lib/set.rb
|
| Parent: | Object |
Set implements a collection of unordered values with no duplicates. This is a hybrid of Array‘s intuitive inter-operation facilities and Hash‘s fast lookup.
Several methods accept any Enumerable object (implementing each) for greater flexibility: new, replace, merge, subtract, |, &, -, ^.
The equality of each couple of elements is determined according to Object#eql? and Object#hash, since Set uses Hash as storage.
Finally, if you are using class Set, you can also use Enumerable#to_set for convenience.
require 'set'
s1 = Set.new [1, 2] # -> #<Set: {1, 2}>
s2 = [1, 2].to_set # -> #<Set: {1, 2}>
s1 == s2 # -> true
s1.add("foo") # -> #<Set: {1, 2, "foo"}>
s1.merge([2, 6]) # -> #<Set: {6, 1, 2, "foo"}>
s1.subset? s2 # -> false
s2.subset? s1 # -> true
Creates a new set containing the elements of the given enumerable object.
If a block is given, the elements of enum are preprocessed by the given block.
# File lib/set.rb, line 64
64: def initialize(enum = nil, &block) # :yields: o
65: @hash ||= Hash.new
66:
67: enum.nil? and return
68:
69: if block
70: enum.each { |o| add(block[o]) }
71: else
72: merge(enum)
73: end
74: end
Returns a new set containing elements common to the set and the given enumerable object.
# File lib/set.rb, line 291
291: def &(enum)
292: enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
293: n = self.class.new
294: enum.each { |o| n.add(o) if include?(o) }
295: n
296: end
Returns true if two sets are equal. The equality of each couple of elements is defined according to Object#eql?.
# File lib/set.rb, line 311
311: def ==(set)
312: equal?(set) and return true
313:
314: set.is_a?(Set) && size == set.size or return false
315:
316: hash = @hash.dup
317: set.all? { |o| hash.include?(o) }
318: end
Returns a new set containing elements exclusive between the set and the given enumerable object. (set ^ enum) is equivalent to ((set | enum) - (set & enum)).
# File lib/set.rb, line 302
302: def ^(enum)
303: enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
304: n = Set.new(enum)
305: each { |o| if n.include?(o) then n.delete(o) else n.add(o) end }
306: n
307: end
Adds the given object to the set and returns self. If the object is already in the set, returns nil.
# File lib/set.rb, line 203
203: def add?(o)
204: if include?(o)
205: nil
206: else
207: add(o)
208: end
209: end
Classifies the set by the return value of the given block and returns a hash of {value => set of elements} pairs. The block is called once for each element of the set, passing the element as parameter.
e.g.:
require 'set'
files = Set.new(Dir.glob("*.rb"))
hash = files.classify { |f| File.mtime(f).year }
p hash # => {2000=>#<Set: {"a.rb", "b.rb"}>,
# 2001=>#<Set: {"c.rb", "d.rb", "e.rb"}>,
# 2002=>#<Set: {"f.rb"}>}
# File lib/set.rb, line 342
342: def classify # :yields: o
343: h = {}
344:
345: each { |i|
346: x = yield(i)
347: (h[x] ||= self.class.new).add(i)
348: }
349:
350: h
351: end
Removes all elements and returns self.
# File lib/set.rb, line 93
93: def clear
94: @hash.clear
95: self
96: end
Do collect() destructively.
# File lib/set.rb, line 236
236: def collect!
237: set = self.class.new
238: each { |o| set << yield(o) }
239: replace(set)
240: end
Deletes the given object from the set and returns self. If the object is not in the set, returns nil.
# File lib/set.rb, line 220
220: def delete?(o)
221: if include?(o)
222: delete(o)
223: else
224: nil
225: end
226: end
Deletes every element of the set for which block evaluates to true, and returns self.
# File lib/set.rb, line 230
230: def delete_if
231: @hash.delete_if { |o,| yield(o) }
232: self
233: end
Divides the set into a set of subsets according to the commonality defined by the given block.
If the arity of the block is 2, elements o1 and o2 are in common if block.call(o1, o2) is true. Otherwise, elements o1 and o2 are in common if block.call(o1) == block.call(o2).
e.g.:
require 'set'
numbers = Set[1, 3, 4, 6, 9, 10, 11]
set = numbers.divide { |i,j| (i - j).abs == 1 }
p set # => #<Set: {#<Set: {1}>,
# #<Set: {11, 9, 10}>,
# #<Set: {3, 4}>,
# #<Set: {6}>}>
# File lib/set.rb, line 369
369: def divide(&func)
370: if func.arity == 2
371: require 'tsort'
372:
373: class << dig = {} # :nodoc:
374: include TSort
375:
376: alias tsort_each_node each_key
377: def tsort_each_child(node, &block)
378: fetch(node).each(&block)
379: end
380: end
381:
382: each { |u|
383: dig[u] = a = []
384: each{ |v| func.call(u, v) and a << v }
385: }
386:
387: set = Set.new()
388: dig.each_strongly_connected_component { |css|
389: set.add(self.class.new(css))
390: }
391: set
392: else
393: Set.new(classify(&func).values)
394: end
395: end
Returns true if the set contains no elements.
# File lib/set.rb, line 88
88: def empty?
89: @hash.empty?
90: end
Equivalent to Set#flatten, but replaces the receiver with the result in place. Returns nil if no modifications were made.
# File lib/set.rb, line 144
144: def flatten!
145: if detect { |e| e.is_a?(Set) }
146: replace(flatten())
147: else
148: nil
149: end
150: end
Returns true if the set contains the given object.
# File lib/set.rb, line 153
153: def include?(o)
154: @hash.include?(o)
155: end
Copy internal hash.
# File lib/set.rb, line 77
77: def initialize_copy(orig)
78: @hash = orig.instance_eval{@hash}.dup
79: end
Returns a string containing a human-readable representation of the set. ("#<Set: {element1, element2, …}>")
# File lib/set.rb, line 401
401: def inspect
402: ids = (Thread.current[InspectKey] ||= [])
403:
404: if ids.include?(object_id)
405: return sprintf('#<%s: {...}>', self.class.name)
406: end
407:
408: begin
409: ids << object_id
410: return sprintf('#<%s: {%s}>', self.class, to_a.inspect[1..-2])
411: ensure
412: ids.pop
413: end
414: end
Merges the elements of the given enumerable object to the set and returns self.
# File lib/set.rb, line 253
253: def merge(enum)
254: if enum.is_a?(Set)
255: @hash.update(enum.instance_eval { @hash })
256: else
257: enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
258: enum.each { |o| add(o) }
259: end
260:
261: self
262: end
Returns true if the set is a proper subset of the given set.
# File lib/set.rb, line 180
180: def proper_subset?(set)
181: set.is_a?(Set) or raise ArgumentError, "value must be a set"
182: return false if set.size <= size
183: all? { |o| set.include?(o) }
184: end
Returns true if the set is a proper superset of the given set.
# File lib/set.rb, line 166
166: def proper_superset?(set)
167: set.is_a?(Set) or raise ArgumentError, "value must be a set"
168: return false if size <= set.size
169: set.all? { |o| include?(o) }
170: end
Equivalent to Set#delete_if, but returns nil if no changes were made.
# File lib/set.rb, line 245
245: def reject!
246: n = size
247: delete_if { |o| yield(o) }
248: size == n ? nil : self
249: end
Replaces the contents of the set with the contents of the given enumerable object and returns self.
# File lib/set.rb, line 100
100: def replace(enum)
101: if enum.class == self.class
102: @hash.replace(enum.instance_eval { @hash })
103: else
104: enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
105: clear
106: enum.each { |o| add(o) }
107: end
108:
109: self
110: end
Returns true if the set is a subset of the given set.
# File lib/set.rb, line 173
173: def subset?(set)
174: set.is_a?(Set) or raise ArgumentError, "value must be a set"
175: return false if set.size < size
176: all? { |o| set.include?(o) }
177: end
Deletes every element that appears in the given enumerable object and returns self.
# File lib/set.rb, line 266
266: def subtract(enum)
267: enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
268: enum.each { |o| delete(o) }
269: self
270: end
Returns true if the set is a superset of the given set.
# File lib/set.rb, line 159
159: def superset?(set)
160: set.is_a?(Set) or raise ArgumentError, "value must be a set"
161: return false if size < set.size
162: set.all? { |o| include?(o) }
163: end
Converts the set to an array. The order of elements is uncertain.
# File lib/set.rb, line 113
113: def to_a
114: @hash.keys
115: end
# File lib/set.rb, line 117
117: def flatten_merge(set, seen = Set.new)
118: set.each { |e|
119: if e.is_a?(Set)
120: if seen.include?(e_id = e.object_id)
121: raise ArgumentError, "tried to flatten recursive Set"
122: end
123:
124: seen.add(e_id)
125: flatten_merge(e, seen)
126: seen.delete(e_id)
127: else
128: add(e)
129: end
130: }
131:
132: self
133: end