Comparing Arrays

D

Derek Cannon

Hello everyone, another easy question from a beginner: How do you create
a method to compare two arrays so that if they share at least 1 common
element it returns true?

For example:
a = %w(m w f)
b = %w(m w)
c = %w(t r)

share_elements?(a,b) #=> true
share_elements?(a,c) #=> false

Thanks for your time,
Derek
 
J

Jean-Julien Fleck

Hello Derek,

2010/4/12 Derek Cannon said:
Hello everyone, another easy question from a beginner: How do you create
a method to compare two arrays so that if they share at least 1 common
element it returns true?

Well, you could use exactly the have_common? method I provided to
compare ranges because arrays also have a to_a method (that does
nothing else than returning the array itself)

def have_common?(r1,r2)
arr =3D r1.to_a & r2.to_a
!arr.empty?
end

a =3D %w(m w f)
b =3D %w(m w)
c =3D %w(t r)
have_common?(a,b)
have_common?(a,c)

Cheers,

--=20
JJ Fleck
PCSI1 Lyc=E9e Kl=E9ber
 
D

Derek Cannon

Thanks Jean, this is the first thing I tried, but I accidentally used
the word "and" instead of &.

What's the difference between & and "and" in this case?
 
P

Priyanka Pathak

Hi,
"&" is bitwise operator. "and" is logical operator & for composition.
that's main difference between "&" and "and". so, as you need to compare
array element use &.
 
J

Jean-Julien Fleck

Hello Derek,

2010/4/12 Derek Cannon said:
Thanks Jean, this is the first thing I tried, but I accidentally used
the word "and" instead of &.

What's the difference between & and "and" in this case?

Well, they have quite nothing in common here :eek:)
On one hand, you are thinking of && which is (almost) the same as
'and' (except concerning precedence).
On the other end, '&' is here the intersection operator defined in the
array class:

Chandler ~>ri 'Array.&'
---------------------------------------------------------------- Array#&
array & other_array

From Ruby 1.8
------------------------------------------------------------------------
Set Intersection---Returns a new array containing elements common
to the two arrays, with no duplicates.

[ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=3D> [ 1, 3 ]


Cheers,

--=20
JJ Fleck
PCSI1 Lyc=E9e Kl=E9ber
 

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
474,158
Messages
2,570,882
Members
47,414
Latest member
djangoframe

Latest Threads

Top