1
+ module Scrooge
2
+
3
+ class SimpleSet < Hash
4
+
5
+ class << self
6
+ ##
7
+ # Creates a new set containing the given objects
8
+ #
9
+ # @return [SimpleSet] The new set
10
+ #
11
+ # @api public
12
+ def []( *ary )
13
+ new ( ary )
14
+ end
15
+ end
16
+
17
+ ##
18
+ # Create a new SimpleSet containing the unique members of _arr_
19
+ #
20
+ # @param [Array] arr Initial set values.
21
+ #
22
+ # @return [Array] The array the Set was initialized with
23
+ #
24
+ # @api public
25
+ def initialize ( arr = [ ] )
26
+ Array ( arr ) . each { |x | self [ x ] = true }
27
+ end
28
+
29
+ ##
30
+ # Add a value to the set, and return it
31
+ #
32
+ # @param [Object] value Value to add to set.
33
+ #
34
+ # @return [SimpleSet] Receiver
35
+ #
36
+ # @api public
37
+ def <<( value )
38
+ self [ value ] = true
39
+ self
40
+ end
41
+
42
+ ##
43
+ # Merge _arr_ with receiver, producing the union of receiver & _arr_
44
+ #
45
+ # s = Extlib::SimpleSet.new([:a, :b, :c])
46
+ # s.merge([:c, :d, :e, f]) #=> #<SimpleSet: {:e, :c, :f, :a, :d, :b}>
47
+ #
48
+ # @param [Array] arr Values to merge with set.
49
+ #
50
+ # @return [SimpleSet] The set after the Array was merged in.
51
+ #
52
+ # @api public
53
+ def merge ( arr )
54
+ super ( arr . inject ( { } ) { |s , x | s [ x ] = true ; s } )
55
+ end
56
+ alias_method :| , :merge
57
+
58
+ ##
59
+ # Invokes block once for each item in the set. Creates an array
60
+ # containing the values returned by the block.
61
+ #
62
+ # s = Extlib::SimpleSet.new([1, 2, 3])
63
+ # s.collect {|s| s + 1} #=> [2, 3, 4]
64
+ #
65
+ # @return [Array] The values returned by the block
66
+ #
67
+ # @api public
68
+ def collect ( &block )
69
+ keys . collect ( &block )
70
+ end
71
+ alias_method :map , :collect
72
+
73
+ ##
74
+ # Get a human readable version of the set.
75
+ #
76
+ # s = SimpleSet.new([:a, :b, :c])
77
+ # s.inspect #=> "#<SimpleSet: {:c, :a, :b}>"
78
+ #
79
+ # @return [String] A human readable version of the set.
80
+ #
81
+ # @api public
82
+ def inspect
83
+ "#<SimpleSet: {#{ keys . map { |x | x . inspect } . join ( ", " ) } }>"
84
+ end
85
+
86
+ # def to_a
87
+ alias_method :to_a , :keys
88
+
89
+ end # SimpleSet
90
+
91
+ end
0 commit comments