[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 коммит произвёл git
Родитель aff41a3669
Коммит 454ac4cbb2
2 изменённых файлов: 19 добавлений и 8 удалений

Просмотреть файл

@ -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,14 +596,16 @@ 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)
enums.each do |enum|
if enum.instance_of?(self.class) if enum.instance_of?(self.class)
@hash.update(enum.instance_variable_get(:@hash)) @hash.update(enum.instance_variable_get(:@hash))
else else
do_with_enum(enum) { |o| add(o) } do_with_enum(enum) { |o| add(o) }
end end
end
self self
end end

Просмотреть файл

@ -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