summaryrefslogtreecommitdiff
path: root/lib/set.rb
diff options
context:
space:
mode:
Diffstat (limited to 'lib/set.rb')
-rw-r--r--lib/set.rb25
1 files changed, 25 insertions, 0 deletions
diff --git a/lib/set.rb b/lib/set.rb
index 0835f8a..5e4e087 100644
--- a/lib/set.rb
+++ b/lib/set.rb
@@ -266,6 +266,14 @@ class Set
self
end
+ # Deletes every element of the set for which block evaluates to
+ # false, and returns self.
+ def keep_if
+ block_given? or return enum_for(__method__)
+ to_a.each { |o| @hash.delete(o) unless yield(o) }
+ self
+ end
+
# Replaces the elements with ones returned by collect().
def collect!
block_given? or return enum_for(__method__)
@@ -284,6 +292,15 @@ class Set
size == n ? nil : self
end
+ # Equivalent to Set#keep_if, but returns nil if no changes were
+ # made.
+ def select!
+ block_given? or return enum_for(__method__)
+ n = size
+ keep_if { |o| yield(o) }
+ size == n ? nil : self
+ end
+
# Merges the elements of the given enumerable object to the set and
# returns self.
def merge(enum)
@@ -563,6 +580,14 @@ class SortedSet < Set
self
end
+ def keep_if
+ block_given? or return enum_for(__method__)
+ n = @hash.size
+ super
+ @keys = nil if @hash.size != n
+ self
+ end
+
def merge(enum)
@keys = nil
super