summaryrefslogtreecommitdiff
path: root/lib/set.rb
diff options
context:
space:
mode:
authorknu <knu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2008-06-03 04:42:32 +0000
committerknu <knu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2008-06-03 04:42:32 +0000
commitea40df71fcd67a1fa16205299ac25c803ab331e2 (patch)
tree42c73a21fff75e41b21ad6bd2d6d3c6f55406510 /lib/set.rb
parenta5c99283201bb66f61c216955dbfbffe683598e5 (diff)
* lib/set.rb (Set#collect, Set#select): Override Enumerable
methods and make them return a set. [ruby-core:17055] (Set#delete_if, Set#collect!, Set#reject!, Set#classify) (Set#divide, Set#delete_if): Return an enumerator if no block is given. (Set#classify): Define an alias `group_by' to override that of Enumerable. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@16771 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'lib/set.rb')
-rw-r--r--lib/set.rb32
1 files changed, 29 insertions, 3 deletions
diff --git a/lib/set.rb b/lib/set.rb
index b925f8e..f73acea 100644
--- a/lib/set.rb
+++ b/lib/set.rb
@@ -250,21 +250,41 @@ class Set
# Deletes every element of the set for which block evaluates to
# true, and returns self.
def delete_if
+ block_given? or return enum_for(__method__)
@hash.delete_if { |o,| yield(o) }
self
end
- # Do collect() destructively.
- def collect!
+ # Calls the given block once for each element and returns a new set
+ # containing the values returned by the block.
+ def collect
+ block_given? or return enum_for(__method__)
set = self.class.new
each { |o| set << yield(o) }
- replace(set)
+ end
+ alias map collect
+
+ # Replaces the values with ones returned by collect().
+ def collect!
+ block_given? or return enum_for(__method__)
+ replace(collect)
end
alias map! collect!
+ # Calls the given block once for each element and returns a new set
+ # containing those elements for which the block returns a true
+ # value.
+ def select
+ block_given? or return enum_for(__method__)
+ set = self.class.new
+ each { |o| set << o if yield(o) }
+ set
+ end
+
# Equivalent to Set#delete_if, but returns nil if no changes were
# made.
def reject!
+ block_given? or return enum_for(__method__)
n = size
delete_if { |o| yield(o) }
size == n ? nil : self
@@ -356,6 +376,8 @@ class Set
# # 2001=>#<Set: {"c.rb", "d.rb", "e.rb"}>,
# # 2002=>#<Set: {"f.rb"}>}
def classify # :yields: o
+ block_given? or return enum_for(__method__)
+
h = {}
each { |i|
@@ -365,6 +387,7 @@ class Set
h
end
+ alias group_by classify
# Divides the set into a set of subsets according to the commonality
# defined by the given block.
@@ -383,6 +406,8 @@ class Set
# # #<Set: {3, 4}>,
# # #<Set: {6}>}>
def divide(&func)
+ func or return enum_for(__method__)
+
if func.arity == 2
require 'tsort'
@@ -501,6 +526,7 @@ class SortedSet < Set
end
def delete_if
+ block_given? or return enum_for(__method__)
n = @hash.size
@hash.delete_if { |o,| yield(o) }
@keys = nil if @hash.size != n