加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

我可以在Ruby中合并两个Set对象吗?

发布时间:2020-12-17 04:23:50 所属栏目:百科 来源:网络整理
导读:我理解 Set class具有合并方法,就像Hash类一样.但是,Set#merge documentation说: Merges the elements of the given enumerable object to the set and returns self. 似乎合并只能在Set和另一个非Set对象之间进行.是这种情况,还是可以合并两套如下? set1.
我理解 Set class具有合并方法,就像Hash类一样.但是,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)作为签名,但没有有用的示例.如果您需要知道Enumerable中哪些类混合,可能很难从这一篇文档中找到可以合并的鸭型鸭.例如,set.merge {foo:’bar’}. to_enum会引发SyntaxError,尽管它是可枚举的:

{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,3}>

set2 = Set.new [3,4,5]
#=> #<Set: {3,5}>

set1.merge set2
#=> #<Set: {1,3,5}>

合并其他可枚举对象,如阵列

但是,您也可以将其他Enumerable对象(如数组)合并到一个集合中.例如:

set = Set.new [1,3}>

set.merge [3,5]
#=> #<Set: {1,5}>

使用Array Union代替

当然,你可能根本不需要套装.比较和对比设置为阵列联合(Array#|).如果您不需要Set类的实际功能,您通常可以直接使用数组执行类似的操作.例如:

([1,4] | [3,5,6]).uniq
#=> [1,6]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读