# Find if an array has any element present in another array

Hi,

I have 2 lists

a=[1,2,3,4]
b=[2,4,6,7,8]

I want to find if there are any elements present in “a” which are also
present in “b”.
I jus wanna “true” or “false” answer if both of the arrays have any
element in common.

Is there any inbuilt functions like “include?” for this purpose??

Charanya N. wrote:

Hi,

I have 2 lists

a=[1,2,3,4]
b=[2,4,6,7,8]

I want to find if there are any elements present in “a” which are also
present in “b”.
I jus wanna “true” or “false” answer if both of the arrays have any
element in common.

Is there any inbuilt functions like “include?” for this purpose??

a=[1,2,3,4]
b=[2,4,6,7,8]

result = a & b
p result

puts (a & b).empty?

–output:–
[2, 4]
false

Le Thu, 30 Apr 2009 05:52:26 -0500,
Charanya N. [email protected] a Ã©crit :

I have 2 lists

a=[1,2,3,4]
b=[2,4,6,7,8]

I want to find if there are any elements present in “a” which are also
present in “b”.
I jus wanna “true” or “false” answer if both of the arrays have any
element in common.

(a-b).nil?

2009/4/30 Charanya N. [email protected]:

I have 2 lists

a=[1,2,3,4]
b=[2,4,6,7,8]

I want to find if there are any elements present in “a” which are also
present in “b”.
I jus wanna “true” or “false” answer if both of the arrays have any
element in common.

You can take the intersection of the two and see if it’s empty.

if (a & b).empty?
puts( ‘Nothing in common’ )
else
puts( ‘Common elements’)
end

Farrel

Thank you.This was What i wanted

as wrote:

(a-b).nil?

result = [1] - [2, 3] #no common elements
p result

result = [2, 3] - [2] #common elements
p result

–output:–
[1]
[3]

Le Thu, 30 Apr 2009 12:57:23 +0200,
as [email protected] a Ã©crit :

I jus wanna “true” or “false” answer if both of the arrays have any
element in common.

(a-b).nil?

Ouch, sorry, (a&b).empty?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.