Issue #14097 has been updated by jeremyevans0 (Jeremy Evans).


ana06 (Ana Maria Martinez Gomez) wrote:
> @jeremyevans0
> 
> > The array class already has a union operator (|) which returns a new array, and in combination with replace you can easily build union. union doesn't seem a common enough need to warrant adding as a separate core method.
> 
> Yes, a operator that is not clear for many people. I think Ruby deserve something more readable and elegant.

The argument against the `|` operator could potentially apply to any operator. Most things are unclear until they are learned.  Someone with no knowledge of English might find the `|` operator more clear than the `union` method.

> Moreover, `union` would allow to make the union of more than 2 arrays at the same time in a much more efficient way than applying `|` several times. So it is not only an "stetic" change, it is also a performance improvement. 

You could build `union` without a nested application of `|`.  No doubt you could get the maximum performance by implementing it in C, but I don't believe the cost of maintaining such code is worth it, considering how often it is used.

> I am not sure what to mean what replace to build a union. Can you please elaborate?

~~~ruby
class Array
  def union(*other)
    ret = self
    other.each{|a| ret |= a}
    replace(ret)
  end
  # or
  def union(*other)
    tmp = other.unshift(self)
    tmp.flatten!(1)
    tmp.uniq!
    replace(tmp)
  end
end
~~~

In similar cases in the past, the recommendation has often been to build the functionality as a gem, and if the gem gets popular and widely used, then it can be considered for inclusion in core.

----------------------------------------
Bug #14097: Add union and difference to Array
https://bugs.ruby-lang.org/issues/14097#change-67794

* Author: ana06 (Ana Maria Martinez Gomez)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
* ruby -v: 
* Backport: 2.3: UNKNOWN, 2.4: UNKNOWN
----------------------------------------
Currently there is a concat method in ruby which does the same as +, but modifying the object. We could introduce a union and difference methods, which would be the equivalent for the `|` and `-` operators. This operators are normally less used due to lack of readability and expressivity. You end seeing thinks like:

```
array.concat(array2).uniq!
```

just because it is more readable. When it could be written like:

```
array |= array2
```

But, as this is not clear for some people, the new method will solve this problem:

```
array.union(array2)
```

And now this is clean and readable, as everybody expect from Ruby, the language focused on simplicity and productivity. ;)


Can I send a PR? :)





-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>