From: gaspode Date: 2006-10-09T21:10:11+09:00 Subject: Re: Removing Duplicate Objects from Object List On Oct 9, 12:45 pm, "Jeff Nyman" wrote: > "gaspode" wrote in messagenews:1160393869.844030.8080@m7g2000cwm.googlegroups.com... > > > How are you storing the Rules in your RuleSet at the moment? Personally > > I'd use an Array (or simply subclass Array) and then you get to use > > Array.uniq without shifting objects back and forth. > Essentially, I have a RuleList class like this: > > > 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? > Plenty > 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. The reason that it isn't working as you expect is that the uniq method uses eql?, which in turn uses the hash method (I think, somebody correct me if I'm full of it). If you implement the hash method (to return the same value for identical Rules) in your Rule class, this should work fine. > > It sounds like you're saying it would be better to not use a Rule class in > the first place. Is that accurate? No, your current Rule class is good. Just implement hash! > > - Jeff Rather than doing: > rules_array = $ruleList.selection.collect { |rule| rule } > rules_array.uniq! you could add a uniq and uniq! method to your RuleList that just delegates the work to the underlying Array def uniq @rules.uniq end def uniq! @rules.uniq! end If it is the case that you NEVER want the same Rule in there twice, just do the check in the append method (also after implementing the hash method) def append(this_rule) @rules.push(this_rule) unless @rules.include?(this_rule) end