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.

Example

  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

Methods

&   +   -   <<   ==   []   ^   add   add?   classify   clear   collect!   delete   delete?   delete_if   difference   divide   each   empty?   flatten   flatten!   flatten_merge   include?   initialize_copy   inspect   intersection   length   map!   member?   merge   new   proper_subset?   proper_superset?   reject!   replace   size   subset?   subtract   superset?   to_a   union   |  

Included Modules

Enumerable

Public Class methods

Creates a new set containing the given objects.

[Source]

    # File lib/set.rb, line 55
55:   def self.[](*ary)
56:     new(ary)
57:   end

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.

[Source]

    # 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

Public Instance methods

Returns a new array containing elements common to the set and the given enumerable object.

[Source]

     # 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
+(enum)

Alias for #|

Returns a new set built by duplicating the set, removing every element that appears in the given enumerable object.

[Source]

     # File lib/set.rb, line 283
283:   def -(enum)
284:     enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
285:     dup.subtract(enum)
286:   end
<<(o)

Alias for add

Returns true if two sets are equal. The equality of each couple of elements is defined according to Object#eql?.

[Source]

     # 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 array containing elements exclusive between the set and the given enumerable object. (set ^ enum) is equivalent to ((set | enum) - (set & enum)).

[Source]

     # File lib/set.rb, line 302
302:   def ^(enum)
303:     enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
304:     n = dup
305:     enum.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. Use merge to add several elements at once.

[Source]

     # File lib/set.rb, line 195
195:   def add(o)
196:     @hash[o] = true
197:     self
198:   end

Adds the given object to the set and returns self. If the object is already in the set, returns nil.

[Source]

     # 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"}>}

[Source]

     # 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.

[Source]

    # File lib/set.rb, line 93
93:   def clear
94:     @hash.clear
95:     self
96:   end

Do collect() destructively.

[Source]

     # 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. Use subtract to delete several items at once.

[Source]

     # File lib/set.rb, line 213
213:   def delete(o)
214:     @hash.delete(o)
215:     self
216:   end

Deletes the given object from the set and returns self. If the object is not in the set, returns nil.

[Source]

     # 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.

[Source]

     # File lib/set.rb, line 230
230:   def delete_if
231:     @hash.delete_if { |o,| yield(o) }
232:     self
233:   end
difference(enum)

Alias for #-

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}>}>

[Source]

     # 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

Calls the given block once for each element in the set, passing the element as parameter.

[Source]

     # File lib/set.rb, line 188
188:   def each
189:     @hash.each_key { |o| yield(o) }
190:     self
191:   end

Returns true if the set contains no elements.

[Source]

    # File lib/set.rb, line 88
88:   def empty?
89:     @hash.empty?
90:   end

Returns a new set that is a copy of the set, flattening each containing set recursively.

[Source]

     # File lib/set.rb, line 138
138:   def flatten
139:     self.class.new.flatten_merge(self)
140:   end

Equivalent to Set#flatten, but replaces the receiver with the result in place. Returns nil if no modifications were made.

[Source]

     # 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.

[Source]

     # File lib/set.rb, line 153
153:   def include?(o)
154:     @hash.include?(o)
155:   end

Copy internal hash.

[Source]

    # 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, …}>")

[Source]

     # 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
intersection(enum)

Alias for #&

length()

Alias for size

map!()

Alias for collect!

member?(o)

Alias for include?

Merges the elements of the given enumerable object to the set and returns self.

[Source]

     # 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.

[Source]

     # 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.

[Source]

     # 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.

[Source]

     # 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.

[Source]

     # 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 the number of elements.

[Source]

    # File lib/set.rb, line 82
82:   def size
83:     @hash.size
84:   end

Returns true if the set is a subset of the given set.

[Source]

     # 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.

[Source]

     # 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.

[Source]

     # 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.

[Source]

     # File lib/set.rb, line 113
113:   def to_a
114:     @hash.keys
115:   end
union(enum)

Alias for #|

Returns a new set built by merging the set and the elements of the given enumerable object.

[Source]

     # File lib/set.rb, line 274
274:   def |(enum)
275:     enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
276:     dup.merge(enum)
277:   end

Protected Instance methods

[Source]

     # 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

[Validate]