From: Michael Halcrow Date: 2002-09-26T06:46:09+09:00 Subject: 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? | ---------------------------------------- | ------------------------