Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I merge two Set objects in Ruby?

Tags:

merge

ruby

set

I understand the Set class has the merge method just as the Hash class does. However, the Set#merge documentation says:

Merges the elements of the given enumerable object to the set and returns self.

It seems that merging can only take place between a Set and another non-Set object. Is that the case, or can I merge two sets as below?

set1.merge(set2)
like image 984
EMW Avatar asked Feb 10 '16 00:02

EMW


1 Answers

Why This Question is Useful

While the OP has been criticized for lack of research effort, it should be pointed out that the Ruby documentation for Set#merge is not friendly for new Rubyists. As of Ruby 2.3.0, it says:

Merges the elements of the given enumerable object to the set and returns self.

It offers merge(enum) as the signature, but no useful examples. If you need to know what classes mix in Enumerable, it can be difficult to grok from just this one piece of documentation what kind of duck-typed ducks can be merged in. For example, set.merge {foo: 'bar'}.to_enum will raise SyntaxError despite the fact that it is enumerable:

{foo: 'bar'}.to_enum.class
#=> Enumerator

{foo: 'bar'}.to_enum.class.include? Enumerable
#=> true

Merging Sets

If you're thinking of Set#merge as creating a set union, then yes: you can merge sets. Consider the following:

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

Merging Other Enumerable Objects Like Arrays

However, you can also merge other Enumerable objects (like arrays) into a set. For example:

set = Set.new [1, 2, 3]
#=> #<Set: {1, 2, 3}>

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

Using Array Union Instead

Of course, you may not need sets at all. Compare and contrast Set to array unions (Array#|). If you don't need the actual features of the Set class, you can often do similar things directly with arrays. For example:

([1, 2, 3, 4] | [3, 4, 5, 6]).uniq
#=> [1, 2, 3, 4, 5, 6]
like image 175
Todd A. Jacobs Avatar answered Sep 21 '22 05:09

Todd A. Jacobs