diff options
author | knu <knu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2017-10-22 12:25:34 +0000 |
---|---|---|
committer | knu <knu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2017-10-22 12:25:34 +0000 |
commit | 34699403fcb93d6fda48ffa7bda733bfc39370f0 (patch) | |
tree | 2c50ce486548899b86a3cb114c93c1333de18be2 | |
parent | d13b9f621af3d2d98b9cd3682c71db917be4e1b2 (diff) | |
download | ruby-34699403fcb93d6fda48ffa7bda733bfc39370f0.tar.gz |
Add `Set#reset`
This method resets the internal state of a set after modification to
existing elements, reindexing and deduplicating them. [Feature #6589]
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@60360 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
-rw-r--r-- | lib/set.rb | 18 | ||||
-rw-r--r-- | test/test_set.rb | 13 |
2 files changed, 31 insertions, 0 deletions
diff --git a/lib/set.rb b/lib/set.rb index b668738ebb..5da196d1e0 100644 --- a/lib/set.rb +++ b/lib/set.rb @@ -477,6 +477,19 @@ class Set @hash.eql?(o.instance_variable_get(:@hash)) end + # Resets the internal state after modification to existing elements + # and returns self. + # + # Elements will be reindexed and deduplicated. + def reset + if @hash.respond_to?(:rehash) + @hash.rehash # This should perform frozenness check. + else + raise "can't modify frozen #{self.class.name}" if frozen? + end + self + end + # Returns true if obj is a member of the set, and false otherwise. # # Used in case statements: @@ -731,6 +744,11 @@ class SortedSet < Set to_a super end + + def rehash + @keys = nil + super + end END end # a hack to shut up warning diff --git a/test/test_set.rb b/test/test_set.rb index 33802410af..37b781c5ca 100644 --- a/test/test_set.rb +++ b/test/test_set.rb @@ -761,6 +761,19 @@ class TC_Set < Test::Unit::TestCase assert_equal(3, set.size) assert_equal(array.uniq.sort, set.sort) end + + def test_reset + [Set, Class.new(Set)].each { |klass| + a = [1, 2] + b = [1] + set = klass.new([a, b]) + + b << 2 + set.reset + + assert_equal(klass.new([a]), set, klass.name) + } + end end class TC_SortedSet < Test::Unit::TestCase |