match at least one element of array to another

  • Thread starter Kenneth Eunjung
  • Start date
K

Kenneth Eunjung

Hi is there a simple way to return true if at least one element of an
array matches at least one element of another array?

For example let's say I have @groups = '4,6'.split(',') and @allowed =
'1,4'.split(',')

I want these to be true because 4 is in both @groups and @allowed.

Thank you!
 
K

Kenneth Eunjung

Hmm I came up with a very inelegant way to do this... that is:

@groups.length + @allowed.length > (@groups | @allowed).length

which is equivalent to 4 > 3 so it evaluates to true.

I guess this works but if you come up with a more elegant way please
share! Thanks.
 
K

Kenneth Eunjung

Okay never mind just came up with a better way:
!(@groups & @allowed).empty?
=> true
 
J

Jean-Julien Fleck

Hello,
I want these to be true because 4 is in both @groups and @allowed.

You could check something like

sum =3D @groups+@allowed
if sum.uniq !=3D sum
what_you_want_to_do_if_same_elements
end

Example:
a,b,c =3D [1,2],[2,3],[4,5] =3D> [[1, 2], [2, 3], [4, 5]]
(a+b).uniq !=3D (a+b) =3D> true
(a+c).uniq !=3D (a+c)
=3D> false

Cheers

--=20
JJ Fleck
PCSI1 Lyc=E9e Kl=E9ber
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,076
Latest member
OrderKetoBeez

Latest Threads

Top