我可以合并 Ruby 中的两个 Set 对象吗?
Can I merge two Set objects in Ruby?
我理解 Set class has the merge method just as the Hash class does. However, the Set#merge documentation 说:
Merges the elements of the given enumerable object to the set and returns self.
合并似乎只能发生在一个Set和另一个非Set对象之间。是这样吗,或者我可以像下面这样合并两个集合吗?
set1.merge(set2)
为什么这个问题有用
虽然 OP 因缺乏研究工作而受到批评,但应该指出 Set#merge 的 Ruby 文档对新 Rubyists 并不友好。从 Ruby 2.3.0 开始,它表示:
Merges the elements of the given enumerable object to the set and returns self.
它提供 merge(enum)
作为签名,但没有有用的示例。如果你需要知道 classes 在 Enumerable 中混合了什么,可能很难从仅此一篇文档中理解什么样的鸭子类型的鸭子可以被合并。例如,set.merge {foo: 'bar'}.to_enum
将引发语法错误,尽管它 是 可枚举的:
{foo: 'bar'}.to_enum.class
#=> Enumerator
{foo: 'bar'}.to_enum.class.include? Enumerable
#=> true
合并集合
如果您将 Set#merge 视为创建集合并集,那么可以:您可以合并集合。考虑以下因素:
require 'set'
set1 = Set.new [1, 2, 3]
#=> #<Set: {1, 2, 3}>
set2 = Set.new [3, 4, 5]
#=> #<Set: {3, 4, 5}>
set1.merge set2
#=> #<Set: {1, 2, 3, 4, 5}>
像数组一样合并其他可枚举对象
但是,您也可以将其他 Enumerable 对象(如数组)合并到一个集合中。例如:
set = Set.new [1, 2, 3]
#=> #<Set: {1, 2, 3}>
set.merge [3, 4, 5]
#=> #<Set: {1, 2, 3, 4, 5}>
改用数组联合
当然,您可能根本不需要套装。比较对比 Set to array unions (Array#|)。如果你不需要 Set class 的实际功能,你通常可以直接用数组做类似的事情。例如:
([1, 2, 3, 4] | [3, 4, 5, 6]).uniq
#=> [1, 2, 3, 4, 5, 6]
我理解 Set class has the merge method just as the Hash class does. However, the Set#merge documentation 说:
Merges the elements of the given enumerable object to the set and returns self.
合并似乎只能发生在一个Set和另一个非Set对象之间。是这样吗,或者我可以像下面这样合并两个集合吗?
set1.merge(set2)
为什么这个问题有用
虽然 OP 因缺乏研究工作而受到批评,但应该指出 Set#merge 的 Ruby 文档对新 Rubyists 并不友好。从 Ruby 2.3.0 开始,它表示:
Merges the elements of the given enumerable object to the set and returns self.
它提供 merge(enum)
作为签名,但没有有用的示例。如果你需要知道 classes 在 Enumerable 中混合了什么,可能很难从仅此一篇文档中理解什么样的鸭子类型的鸭子可以被合并。例如,set.merge {foo: 'bar'}.to_enum
将引发语法错误,尽管它 是 可枚举的:
{foo: 'bar'}.to_enum.class
#=> Enumerator
{foo: 'bar'}.to_enum.class.include? Enumerable
#=> true
合并集合
如果您将 Set#merge 视为创建集合并集,那么可以:您可以合并集合。考虑以下因素:
require 'set'
set1 = Set.new [1, 2, 3]
#=> #<Set: {1, 2, 3}>
set2 = Set.new [3, 4, 5]
#=> #<Set: {3, 4, 5}>
set1.merge set2
#=> #<Set: {1, 2, 3, 4, 5}>
像数组一样合并其他可枚举对象
但是,您也可以将其他 Enumerable 对象(如数组)合并到一个集合中。例如:
set = Set.new [1, 2, 3]
#=> #<Set: {1, 2, 3}>
set.merge [3, 4, 5]
#=> #<Set: {1, 2, 3, 4, 5}>
改用数组联合
当然,您可能根本不需要套装。比较对比 Set to array unions (Array#|)。如果你不需要 Set class 的实际功能,你通常可以直接用数组做类似的事情。例如:
([1, 2, 3, 4] | [3, 4, 5, 6]).uniq
#=> [1, 2, 3, 4, 5, 6]