From: Derek Cannon on
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
--
Posted via http://www.ruby-forum.com/.

From: Jean-Julien Fleck on
Hello Derek,

2010/4/12 Derek Cannon <novellterminator(a)gmail.com>:
> 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 = r1.to_a & r2.to_a
!arr.empty?
end

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

Cheers,

--
JJ Fleck
PCSI1 Lycée Kléber

From: Derek Cannon on
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?
--
Posted via http://www.ruby-forum.com/.

From: GianFranco Bozzetti on

"Derek Cannon" <novellterminator(a)gmail.com> wrote in message
news:24f32d608e99f3ef93bca701fdfe130c(a)ruby-forum.com...
> 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
> --
> Posted via http://www.ruby-forum.com/.
>
An answer:

# array_cmp.rb
def share_elements?(a1,a2)
not (a1 & a2).empty?
end

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

r = share_elements?(a,b) #=> true
printf("%12s/%-12s => %s\n", a.inspect.to_s, b.inspect.to_s, r.to_s)
r = share_elements?(a,c) #=> false
printf("%12s/%-12s => %s\n", a.inspect.to_s, c.inspect.to_s, r.to_s)
exit(0)

Hth gfb


From: Priyanka Pathak on
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 &.
--
Posted via http://www.ruby-forum.com/.