From: Hugh Sasse Staff Elec Eng Date: 2001-06-23T01:23:07+09:00 Subject: [ruby-talk:16774] Re: uniq and "equivalence" On Sat, 23 Jun 2001, ts wrote: > >>>>> "H" == Hugh Sasse Staff Elec Eng writes: > > >> Array#uniq make first an hash, then delete the elements. > > H> is that Object#hash() or Hash.new()? > > Hash::new Ok, I see which elements can be deleted now... > > H> Object#hash must return a fixnum such that > H> a.eql?(b) means a.hash = b.hash. That is a pretty tall > H> order for arrays of floats. Has anyone any suggestions > H> on how to proceed? > > Define a #hash method for your class Trapezoidal_fitness, actually because > it's not defined it use the default #hash function which is the id of the > object. That's what I don't want, but how can one map a 4-D set of floats on to Fixnums? Maybe I should redefine uniq: #!/usr/local/bin/ruby -w class Array def uniq finished = false other = self.dup while !finished finished = true other.each { |val| left = self.index(val) right = self.rindex(val) next if left == right finished = false while right != left self.delete_at(right) right = self.rindex(val) end retry # restart the each... } end self end end class Wotsit attr_reader :a, :b def initialize(x,y) @a,@b = x, y end def ==(other) @a == other.a && @b == other.b end end if __FILE__ == $0 require "runit/testcase" require 'runit/cui/testrunner' require 'runit/testsuite' class Testing_Array < RUNIT::TestCase def test_feature1 thing1 = Wotsit.new(1,2) thing2 = Wotsit.new(1,2) thing3 = Wotsit.new(2,2) thing4 = Wotsit.new(2,2) thing5 = Wotsit.new(2,2) mine = [thing1,thing2,thing3,thing3,thing3, thing4,thing5,thing2,thing3,thing5] expected = [thing1,thing3] assert_equal(expected, mine.uniq) end end RUNIT::CUI::TestRunner.run(Testing_Array.suite) end which gives uniq_tmp.rb:4: warning: discarding old uniq /usr/local/lib/ruby/site_ruby/1.6/runit/assert.rb:146: warning: concat (...) interpreted as method call /usr/local/lib/ruby/site_ruby/1.6/runit/assert.rb:158: warning: concat (...) interpreted as method call Testing_Array#test_feature1 . Time: 0.001764 OK (1/1 tests 1 asserts) Caffeine underflow: Maybe I don't need the retry after messing up all the indices by deletion(s). > > > Guy Decoux > Hugh