Hi,
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)
Watch it, though, the comparison is based on Object#hash:
irb for ruby-1.9.3-r27796
class N
attr_reader :n
def initiaize(n)
@n = n
end
end
[N.new(1), N.new(2)] & [N.new(2), N.new(3)]
=>
[N.new(2), N.new(2)].map(&:hash)
=> [2562895216144860017, -4480771430923711611]
So, to make it works as expected:
class N
def hash
@n.hash
end
def eql?(n)
@n == n.n
end
end
[N.new(2), N.new(2)].map(&:hash)
=> [-1851237208519162443, -1851237208519162443]
[N.new(1), N.new(2)] & [N.new(2), N.new(3)]
=> [#<N:0x00000101161b40>] # 2
It sounds like a bug to me this ...
(or at least documentation not clear:
"Set Intersection---Returns a new array containing elements common to the two
arrays, with no duplicates.")
Programming Ruby is more complete:
"Set Intersection—Returns a new array containing elements common to
the two arrays, with no duplicates.(identical)
The rules for comparing elements are the same as for hash keys. If you
need setlike behavior, see the library class Set"
then why is it called Set Intersection?
(anyway, Set#& behaves the same)