[ruby-core:95257] [Ruby master Feature#16155] Add an Array#intersection method
From:
sin@...
Date:
2019-10-07 06:57:11 UTC
List:
ruby-core #95257
Issue #16155 has been updated by prajjwal (Prajjwal Singh).
Implementation is currently based on `Array#&`, which is elegant but might end up allocating a whole bunch of arrays holding intermediate results. If needed I can implement `Array#intersection` so it only allocates the result array once, but then I would like to rewrite `Array#&` in terms of `Array#intersection` to keep things DRY.
```ruby
static VALUE
rb_ary_intersection_multi(int argc, VALUE *argv, VALUE ary)
{
VALUE result = rb_ary_dup(ary);
int i;
for (i = 0; i < argc; i++) {
result = rb_ary_and(result, argv[i]);
}
return result;
}
```
Let me know what you think.
----------------------------------------
Feature #16155: Add an Array#intersection method
https://bugs.ruby-lang.org/issues/16155#change-81934
* Author: connorshea (Connor Shea)
* Status: Open
* Priority: Normal
* Assignee:
* Target version:
----------------------------------------
`Array#union` and `Array#difference` were added in Ruby 2.6 ([see this bug](https://bugs.ruby-lang.org/issues/14097)), but an equivalent for `&` (intersection) was not.
I'd like to propose `Array#intersection`. This would essentially just be a more readable alias for `Array#&`, in the same way that `Array#|` and `Array#-` have `Array#union` and `Array#difference`.
I think it'd make sense for Ruby to have a more readable name for this method :)
Current syntax:
``` ruby
[ 1, 1, 3, 5 ] & [ 3, 2, 1 ] #=> [ 1, 3 ]
[ 'a', 'b', 'b', 'z' ] & [ 'a', 'b', 'c' ] #=> [ 'a', 'b' ]
```
What I'd like to see added:
```ruby
[ 1, 1, 3, 5 ].intersection([ 3, 2, 1 ]) #=> [ 1, 3 ]
[ 'a', 'b', 'b', 'z' ].intersection([ 'a', 'b', 'c' ]) #=> [ 'a', 'b' ]
```
mame asks about `intersection` [in this comment](https://bugs.ruby-lang.org/issues/14097#note-26) on the `union`/`difference` bug, but as far as I can tell it was never addressed.
[`Set#intersection`](http://ruby-doc.org/stdlib-2.6.2/libdoc/set/rdoc/Set.html#method-i-intersection) already exists and is an alias for `Set#&`, so there's precedent for such a method to exist.
Thanks for Ruby, I enjoy using it a lot! :)
Related links:
- [PR for `union`](https://github.com/ruby/ruby/pull/1747)
- [PR for `difference`](https://github.com/ruby/ruby/pull/1758)
- [Bug for adding `union` and `difference` methods](https://bugs.ruby-lang.org/issues/14097)
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>