[ruby/set] Set#merge takes many enumerable objects like Hash#merge! does

https://github.com/ruby/set/commit/becaca994d
This commit is contained in:
Akinori MUSHA 2023-02-24 15:58:19 +09:00 committed by git
parent aff41a3669
commit 454ac4cbb2
2 changed files with 19 additions and 8 deletions

View File

@ -152,7 +152,7 @@
# If the given object is not an element in the set, # If the given object is not an element in the set,
# adds it and returns +self+; otherwise, returns +nil+. # adds it and returns +self+; otherwise, returns +nil+.
# - \#merge: # - \#merge:
# Adds each given object to the set; returns +self+. # Merges the elements of each given enumerable object to the set; returns +self+.
# - \#replace: # - \#replace:
# Replaces the contents of the set with the contents # Replaces the contents of the set with the contents
# of a given enumerable. # of a given enumerable.
@ -596,13 +596,15 @@ class Set
# Equivalent to Set#select! # Equivalent to Set#select!
alias filter! select! alias filter! select!
# Merges the elements of the given enumerable object to the set and # Merges the elements of the given enumerable objects to the set and
# returns self. # returns self.
def merge(enum) def merge(*enums)
if enum.instance_of?(self.class) enums.each do |enum|
@hash.update(enum.instance_variable_get(:@hash)) if enum.instance_of?(self.class)
else @hash.update(enum.instance_variable_get(:@hash))
do_with_enum(enum) { |o| add(o) } else
do_with_enum(enum) { |o| add(o) }
end
end end
self self

View File

@ -587,10 +587,19 @@ class TC_Set < Test::Unit::TestCase
def test_merge def test_merge
set = Set[1,2,3] set = Set[1,2,3]
ret = set.merge([2,4,6]) ret = set.merge([2,4,6])
assert_same(set, ret) assert_same(set, ret)
assert_equal(Set[1,2,3,4,6], set) assert_equal(Set[1,2,3,4,6], set)
set = Set[1,2,3]
ret = set.merge()
assert_same(set, ret)
assert_equal(Set[1,2,3], set)
set = Set[1,2,3]
ret = set.merge([2,4,6], Set[4,5,6])
assert_same(set, ret)
assert_equal(Set[1,2,3,4,5,6], set)
end end
def test_subtract def test_subtract