Forum: Ruby find if an array has any element present in another array

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Charanya N. (Guest)
on 2009-04-30 14:52
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.
7stud -. (Guest)
on 2009-04-30 14:59
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
as (Guest)
on 2009-04-30 15:02
(Received via mailing list)
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?
Farrel L. (Guest)
on 2009-04-30 15:05
(Received via mailing list)
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
Charanya N. (Guest)
on 2009-04-30 15:11
Thank you.This was What i wanted
7stud -. (Guest)
on 2009-04-30 15:13
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]
as (Guest)
on 2009-04-30 15:19
(Received via mailing list)
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?
This topic is locked and can not be replied to.