Find if an array has any element present in another array


#1

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??

Thanks in Advance.


#2

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??

Thanks in Advance.

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

result = a & b
p result

puts (a & b).empty?

–output:–
[2, 4]
false


#3

Le Thu, 30 Apr 2009 05:52:26 -0500,
Charanya N. removed_email_address@domain.invalid 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?


#4

2009/4/30 Charanya N. removed_email_address@domain.invalid:

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


#5

Thank you.This was What i wanted


#6

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]


#7

Le Thu, 30 Apr 2009 12:57:23 +0200,
as removed_email_address@domain.invalid 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?