summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormarcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2010-05-30 13:19:09 +0000
committermarcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2010-05-30 13:19:09 +0000
commit1d06ff976184b4956a58a867132061c6a5902cd6 (patch)
tree21ec5d63c70046c316b45d991a1c6ea4a5003bd5
parentd346b26be43140e8fb26f9e0cf8ea2793ba925ed (diff)
* lib/set.rb (keep_if, select!): New methods [ruby-core:29749]
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@28096 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
-rw-r--r--ChangeLog4
-rw-r--r--NEWS5
-rw-r--r--lib/set.rb25
3 files changed, 34 insertions, 0 deletions
diff --git a/ChangeLog b/ChangeLog
index a14bbfa..30dcff9 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,7 @@
+Sun May 30 22:18:49 2010 Marc-Andre Lafortune <ruby-core@marc-andre.ca>
+
+ * lib/set.rb (keep_if, select!): New methods [ruby-core:29749]
+
Sun May 30 21:51:59 2010 Yusuke Endoh <mame@tsg.ne.jp>
* test/rake/test_application.rb: update a test because of r28089.
diff --git a/NEWS b/NEWS
index 7d11950..4a17089 100644
--- a/NEWS
+++ b/NEWS
@@ -373,6 +373,11 @@ with all sufficient information, see the ChangeLog file.
* Readline.completion_proc= accepts nil.
nil means to use default completion proc.
+* set
+ * new methods:
+ * Set#keep_if
+ * Set#select!
+
* time
* incompatible changes:
* Time.parse raises ArgumentError when no date information.
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