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.
#1 [ruby-core:89273] Updated by shyouhei (Shyouhei Urabe) 13 days 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) 12 days 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.
#4 [ruby-core:89309] Updated by c4am95 (Travis Hunter) 9 days 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.
#5 [ruby-core:89321] Updated by c4am95 (Travis Hunter) 8 days ago
It also seems like it comes up fairly commonly on stackoverflow/blogs: