From: gaspode Date: 2006-10-09T20:40:11+09:00 Subject: Re: Removing Duplicate Objects from Object List On Oct 9, 12:16 pm, "Jeff Nyman" wrote: > Greetings all. > > Does anyone have a good idea of how to write a loop that checks if two > objects are equal? By "equal" here I refer to the 'eql' method, to test if > the objects have the same value. > > I have set of Rule objects that will be stored in a RuleList object. I know > how to cycle through the RuleList. I'm just doing this: > > $ruleList.selection.each { |rule| > ... > > }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. > > Every solution I've tried has ended up either removing objects incorrectly > or not finding the duplicates in the first place. > > Here's an example of some Rule objects: > > @value="203G_OrdUpdateFirst", @point="203G_OrdUpdateFirst"> > @point="203G_OrdUpdateLast"> > @value="203G_OrdUpdateFirst", @point="203G_OrdUpdateFirst"> > @point="203G_OrdUpdateLast"> > > Here is what they look like as strings: > > 203G_OrdUpdateFirst, first after 202G_OrdAdd, 203G_OrdUpdateFirst > 203G_OrdUpdateLast, last, 203G_OrdUpdateLast > 203G_OrdUpdateFirst, first after 202G_OrdAdd, 203G_OrdUpdateFirst > 203G_OrdUpdateLast, last, 203G_OrdUpdateLast > > So as you can see, I have four rules, but actually only two are unique. > (That just happens to be the case here. In other cases, perhaps there will > be six rules, and two will be unique.) > > Can anyone see an efficient way to do this? > > Is it better to just convert these into an array? I know the Array class has > the 'uniq' method. The problem is that I would still need the rules to then > be objects as well. In other words, even if I put all the objects in an > array and modify the array, I would need to reflect the changes in the > object list itself, such that the duplicate objects no longer exist. > > - Jeff Jeff, 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. Stephen