|
3 | 3 | # |
4 | 4 | # set.rb - defines the Set class |
5 | 5 | #++ |
6 | | -# Copyright (c) 2002-2013 Akinori MUSHA <knu@iDaemons.org> |
| 6 | +# Copyright (c) 2002-2016 Akinori MUSHA <knu@iDaemons.org> |
7 | 7 | # |
8 | 8 | # Documentation by Akinori MUSHA and Gavin Sinclair. |
9 | 9 | # |
|
37 | 37 | # Set uses Hash as storage, so you must note the following points: |
38 | 38 | # |
39 | 39 | # * Equality of elements is determined according to Object#eql? and |
40 | | -# Object#hash. |
| 40 | +# Object#hash. Use Set#compare_by_identity to make a set compare |
| 41 | +# its elements by their identity. |
41 | 42 | # * Set assumes that the identity of each element does not change |
42 | 43 | # while it is stored. Modifying an element of a set will render the |
43 | 44 | # set to an unreliable state. |
@@ -91,6 +92,23 @@ def initialize(enum = nil, &block) # :yields: o |
91 | 92 | end |
92 | 93 | end |
93 | 94 |
|
| 95 | + # Makes the set compare its elements by their identity and returns |
| 96 | + # self. This method may not be supported by all subclasses of Set. |
| 97 | + def compare_by_identity |
| 98 | + if @hash.respond_to?(:compare_by_identity) |
| 99 | + @hash.compare_by_identity |
| 100 | + self |
| 101 | + else |
| 102 | + raise NotImplementedError, "#{self.class.name}\##{__method__} is not implemented" |
| 103 | + end |
| 104 | + end |
| 105 | + |
| 106 | + # Returns true if the set will compare its elements by their |
| 107 | + # identity. Also see Set#compare_by_identity. |
| 108 | + def compare_by_identity? |
| 109 | + @hash.respond_to?(:compare_by_identity?) && @hash.compare_by_identity? |
| 110 | + end |
| 111 | + |
94 | 112 | def do_with_enum(enum, &block) # :nodoc: |
95 | 113 | if enum.respond_to?(:each_entry) |
96 | 114 | enum.each_entry(&block) if block |
|
0 commit comments