Can I combine two Set objects in Ruby?

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

Combines the elements of a given enumerated object with a set and returns self.

It seems that merging can only happen between Set and an object other than Set. Is this the case, or can I combine the two sets as shown below?

set1.merge(set2) 
+5
source share
1 answer

Why is this question helpful?

While the OP is criticized for the lack of research efforts, it should be noted that the Ruby documentation for Set # merge is not friendly to new rubists. Starting with Ruby 2.3.0, it says:

Combines the elements of a given enumerated object with a set and returns self.

It offers merge(enum) as a signature, but does not contain useful examples. If you need to know which classes are mixed in Enumerable , it can be difficult to get only one piece of documentation, which duck-typed ducks can be combined. For example, set.merge {foo: 'bar'}.to_enum raises a SyntaxError, although it will list:

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

Merge sets

If you are thinking of Installing # merge as creating a collection union, then yes: you can merge the 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}> 

Combining other enumerated objects, such as arrays

However, you can also combine other Enumerable objects (such as arrays) into a set. For instance:

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

Using Union Array Instead

Of course, you may not need kits at all. Comparison and contrast Set to combine arrays ( Array # | ). If you don't need the actual functions of the Set class, you can often do similar things directly with arrays. For instance:

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

Source: https://habr.com/ru/post/1242668/


All Articles