find if an array has any element present in another array

C

Charanya Nagarajan

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

as

Le Thu, 30 Apr 2009 05:52:26 -0500,
Charanya Nagarajan said:
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?
 
7

7stud --

Charanya said:
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
 
F

Farrel Lifson

2009/4/30 Charanya Nagarajan said:
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
 
A

as

Le Thu, 30 Apr 2009 12:57:23 +0200,
as said:
Le Thu, 30 Apr 2009 05:52:26 -0500,
Charanya Nagarajan said:
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?

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

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

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top