Module: RMTools::SmarterSetOps

Included in:
Array, Set
Defined in:
lib/rmtools/enumerable/set_ops.rb

Overview

Builtin methods overwrite. Why should we do zillions of cycles just for ensure ‘A | [] = A - [] = A or A & [] = []` ? Though #- and #& should be improved within C-extension to break loop when no items have had lost in self (Or not? Don’t remember what I had on my mind while I’ve being writing this)

Class Method Summary collapse

Class Method Details

.included(acceptor) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/rmtools/enumerable/set_ops.rb', line 11

def self.included(acceptor)
  acceptor.class_eval {
    alias :union :|
    alias :coallition :+
    alias :subtraction :-
    alias :intersection :&
    # :& won't work this way if :intersection will be protected
    protected :union, :coallition, :subtraction
    
    def |(ary) 
      return ary.uniq if empty?
      return uniq if ary.respond_to? :empty? and ary.empty?
      
      union ary
    end
    
    def +(ary) 
      if empty?
        return [] if ary.respond_to? :empty? and ary.empty?
        ary.dup
      end
      return dup if ary.respond_to? :empty? and ary.empty?
      
      coallition ary
    end
    
    def -(ary) 
      return [] if empty?
      return dup if ary.respond_to? :empty? and ary.empty?
      
      subtraction ary
    end
    
    def &(ary) 
      return [] if empty? or (ary.respond_to? :empty? and ary.empty?)
      return ary.intersection self if size < ary.size
      
      intersection ary
    end
    
    def ^(ary)
      return [dup, ary.dup] if empty? or (ary.respond_to? :empty? and ary.empty?)
      return [[], []] if self == ary
      
      common = intersection ary
      [self - common, ary - common]
    end
    
    alias :diff :^
    
    def intersects?(ary)
      (self & ary).any?
    end
    alias :x? :intersects?
    
    def =~(ary)
      (self - ary).empty?
    end
    alias :is_subset_of? :=~
  }
  super
end