# Set Union on Array of Objects

Why do array subtraction and array union not behave in the same manner
when operating on an array of user-defined objects? Specifically, how
can I get the Array union operator to use the user-defined “==” method
of the objects, as the Array subtraction operator does? What is the best
way to get what I expect?

Thanks,
Mike

#!/usr/bin/ruby

class Foo

attr_accessor :a, :b

def initialize( a, b )
@a = a
@b = b
end

def ==( foo )
puts "Foo.== Called!"
if( \$comparemode == 0 )
@a == foo.a
else
@b == foo.b
end
end

def to_s
"#{@a}:#{@b}"
end

end

x = [ Foo.new( ‘a’, 1 ), Foo.new( ‘a’, 2 ) ]
y = [ Foo.new( ‘a’, 2 ), Foo.new( ‘b’, 3 ) ]

puts "Set Subtraction on Attribute:"
puts “EXPECT (empty)”
\$comparemode = 0
puts x - y
puts "Set Subtraction on Value:"
puts “EXPECT a:1”
\$comparemode = 1
puts x - y
puts "Set Union on Attribute:"
puts “EXPECT a:1, b:3”
\$comparemode = 0
puts x | y
puts "Set Union on Value:"
puts “EXPECT a:1, a:2, b:3”
\$comparemode = 1
puts x | y

···

Set Subtraction on Attribute:
EXPECT (empty)
Foo.== Called!
Foo.== Called!
Set Subtraction on Value:
EXPECT a:1
Foo.== Called!
Foo.== Called!
Foo.== Called!
a:1
Set Union on Attribute:
EXPECT a:1, b:3
a:1
a:2
a:2
b:3
Set Union on Value:
EXPECT a:1, a:2, b:3
a:1
a:2
a:2
b:3

---------------------------------------- | ------------------------
Michael Halcrow | mhalcrow@byu.edu
Research Assistant, Network Security Lab | Dept. of Comp. Science
> Brigham Young University

What has it got on its portses?

Hi,

You have a very interesting case. It seems that while array subtraction
is implemented internally using “rb_equal()” which invokes the
“==” method, array union (and some others) is implemented using some
hashing of the actual objects themselves. I don’t know a way to get what
you expect except to implement explicitly the method yourself in Ruby.

(Probably this is another candidate for “Things That Newcomers to Ruby
Should Know”? )

Regards,

Bill

···

============================================================================
Michael Halcrow mah69@email.byu.edu wrote:

Why do array subtraction and array union not behave in the same manner
when operating on an array of user-defined objects? Specifically, how
can I get the Array union operator to use the user-defined “==” method
of the objects, as the Array subtraction operator does? What is the best
way to get what I expect?

Thanks,
Mike

Hello William,

Thursday, September 26, 2002, 7:04:12 AM, you wrote:

Why do array subtraction and array union not behave in the same manner
when operating on an array of user-defined objects? Specifically, how
can I get the Array union operator to use the user-defined “==” method
of the objects, as the Array subtraction operator does? What is the best
way to get what I expect?

such methods can try to use

1. hash() and sort_by
2. <=> and sort
3. = in O(n*n) algorithm
···

Best regards,
Bulat mailto:bulatz@integ.ru