Feature #15198


Added by c4am95 (Travis Hunter) 10 months ago. Updated 9 months ago.

Target version:


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?


Updated by shyouhei (Shyouhei Urabe) 10 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.

Updated by c4am95 (Travis Hunter) 10 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.

Updated by shevegen (Robert A. Heiler) 10 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). :)

Updated by c4am95 (Travis Hunter) 10 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