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

Thanks in Advance.

···

--
Posted via http://www.ruby-forum.com/.

Charanya Nagarajan 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

···

--
Posted via http://www.ruby-forum.com/\.

(a-b).nil?

···

Le Thu, 30 Apr 2009 05:52:26 -0500, Charanya Nagarajan <charanya.nagarajan@tcs.com> 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.

--
Arnaud Schmittbuhl

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

···

2009/4/30 Charanya Nagarajan <charanya.nagarajan@tcs.com>:

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.

--
Aimred - Ruby Development and Consulting

Thank you.This was What i wanted

···

--
Posted via http://www.ruby-forum.com/.

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]

···

--
Posted via http://www.ruby-forum.com/\.

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

···

Le Thu, 30 Apr 2009 12:57:23 +0200, as <nosp@m.invalid> a écrit :

Le Thu, 30 Apr 2009 05:52:26 -0500, > Charanya Nagarajan <charanya.nagarajan@tcs.com> 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?

--
Arnaud Schmittbuhl