Project

General

Profile

Feature #15198

Array#intersect?

Added by c4am95 (Travis Hunter) 2 months ago. Updated 2 months ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:89269]

Description

I frequently find myself needing to determine if two arrays intersect but not actually caring about the intersection, so I write code like:

(a1 & a2).any?

It would be nice to have an intersect? convenience method on Array to perform this query.

ruby#1972: Add Array#intersect?

History

#1 [ruby-core:89273] Updated by shyouhei (Shyouhei Urabe) 2 months ago

  • Interesting. Can you share a bit more detail about your "if two arrays intersect but not actually caring about the intersection" use case? For instance if you have open sourced such code, a URL for it helps us a lot.

  • If you have zero interest to the intersection itself I think you can avoid creating the temporary array.

#2 [ruby-core:89287] Updated by c4am95 (Travis Hunter) 2 months ago

The most recent example I encountered was authorizing a user in a Rails endpoint. Each user has a list of abilities, and each endpoint has a list of abilities that is authorized to perform the action. We just need to check if there is an intersection between the two lists.

I updated the PR to avoid creating the intermediate array.

#3 [ruby-core:89297] Updated by shevegen (Robert A. Heiler) 2 months ago

Demonstrated use cases helps the core team & matz assess on the usefulness of a proposed
change, which can help in accepting issue requests ultimately in the long run (if the
use case is considered sufficiently useful). :)

#4 [ruby-core:89309] Updated by c4am95 (Travis Hunter) 2 months ago

I threw together an example in a gist which is very similar to the use case I described. I have also run into numerous other situations where this functionality would have been useful.

I added some comments in the gist but I'll cross-post them here for reference:

The current behavior creates an intermediate array for both intersection tests when the resulting array is clearly not needed. With the desired behavior, we could avoid creating the intermediate array and produce a faster best case runtime.

Also available in: Atom PDF