summaryrefslogtreecommitdiff
path: root/lib/set.rb
diff options
context:
space:
mode:
authorknu <knu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2010-02-11 17:38:05 +0000
committerknu <knu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2010-02-11 17:38:05 +0000
commite1d9adcc84624fd056142c9d079d16a217cf5b58 (patch)
tree7818e7304a436710fb637de4409874e47aa51647 /lib/set.rb
parent36ff32040e6dceb8c3a6a67b11e663db6dcd6f06 (diff)
Fri Feb 12 02:27:39 2010 Akinori MUSHA <knu@iDaemons.org>
* lib/set.rb (Set#initialize, Set#replace, Set#merge) (Set#subtract, Set#&): Fix duck type tests. [ruby-core:28078] * lib/set.rb (Set#initialize, Set#replace, Set#merge) (Set#subtract, Set#&): Try #each if #each_entry fails. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@26648 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'lib/set.rb')
-rw-r--r--lib/set.rb26
1 files changed, 16 insertions, 10 deletions
diff --git a/lib/set.rb b/lib/set.rb
index 3e22a8c..0835f8a 100644
--- a/lib/set.rb
+++ b/lib/set.rb
@@ -70,13 +70,23 @@ class Set
enum.nil? and return
if block
- enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable"
- enum.each_entry { |o| add(block[o]) }
+ do_with_enum(enum) { |o| add(block[o]) }
else
merge(enum)
end
end
+ def do_with_enum(enum, &block)
+ if enum.respond_to?(:each_entry)
+ enum.each_entry(&block)
+ elsif enum.respond_to?(:each)
+ enum.each(&block)
+ else
+ raise ArgumentError, "value must be enumerable"
+ end
+ end
+ private :do_with_enum
+
# Copy internal hash.
def initialize_copy(orig)
@hash = orig.instance_eval{@hash}.dup
@@ -123,9 +133,8 @@ class Set
if enum.class == self.class
@hash.replace(enum.instance_eval { @hash })
else
- enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable"
clear
- enum.each_entry { |o| add(o) }
+ merge(enum)
end
self
@@ -281,8 +290,7 @@ class Set
if enum.instance_of?(self.class)
@hash.update(enum.instance_variable_get(:@hash))
else
- enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable"
- enum.each_entry { |o| add(o) }
+ do_with_enum(enum) { |o| add(o) }
end
self
@@ -291,8 +299,7 @@ class Set
# Deletes every element that appears in the given enumerable object
# and returns self.
def subtract(enum)
- enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable"
- enum.each_entry { |o| delete(o) }
+ do_with_enum(enum) { |o| delete(o) }
self
end
@@ -314,9 +321,8 @@ class Set
# Returns a new set containing elements common to the set and the
# given enumerable object.
def &(enum)
- enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable"
n = self.class.new
- enum.each_entry { |o| n.add(o) if include?(o) }
+ do_with_enum(enum) { |o| n.add(o) if include?(o) }
n
end
alias intersection & ##