From: Daniel Harple Date: 2006-10-09T21:05:32+09:00 Subject: Re: Removing Duplicate Objects from Object List On Oct 9, 2006, at 1:50 PM, Jeff Nyman wrote: > The problem is that I need to go through each rule and check if it > is equal > to *any* of the other rules that are in the list. If a duplicate is > found, > one of the duplicate rules should be removed. > class Rule > attr_accessor :point, :filter, :value > > def initialize(point, filter, value) > @point = point > @filter = filter > @value = value > end > end > > When a rule object needs to be added to the list, I do this: > > $ruleList.append(Rule.new(step.point2, rule, value)) > > Does that give enough detail? > > In playing around a bit more, I tried this: > > rules_array = $ruleList.selection.collect { |rule| rule } > > Then I tried: > > rules_array.uniq! > > The problem is that this finds nothing as a duplicate. But that > makes sense > (I think) because the object ID is probably being considered as > part of the > test and those will, of course, not be duplicates. > > It sounds like you're saying it would be better to not use a Rule > class in > the first place. Is that accurate? You should implement #eql? and #hash methods on your class, and store all instances in a [Set](http://ruby-doc.org/stdlib/libdoc/set/rdoc/ classes/Set.html). require "set" class Rule attr_accessor :point, :filter, :value def initialize(point, filter, value) @point = point @filter = filter @value = value end def eql?(rule) rule.point.eql?(@point) && rule.filter.eql?(@filter) && rule.value.eql?(@value) end def hash @point.hash + @filter.hash + @value.hash end end rules_set = Set.new rules_set << Rule.new(1, 1, 1) rules_set << Rule.new(1, 1, 1) # duplicate rule rules_set << Rule.new(1, 1, 2) rules_set.size # => 2 rules_set # => #, #}> -- Daniel