Mike
10/10/2006 3:18:00 PM
uniq is failing because, even though the attributes of each instance of
the rule is 'eq' to the other, the compared instances are different.
class Foo
def initialize(a,b)
@a = a
@b = b
end
end
x = [Foo.new(:a, :b), Foo.new(:c, :d), Foo.new(:a, :b)]
p x
p x.uniq
ruby tst.rb
[#<Foo:0x3b6128 @a=:a, @b=:b>, #<Foo:0x3b6114 @a=:c, @b=:d>,
#<Foo:0x3b6100 @a=:a, @b=:b>]
[#<Foo:0x3b6128 @a=:a, @b=:b>, #<Foo:0x3b6114 @a=:c, @b=:d>,
#<Foo:0x3b6100 @a=:a, @b=:b>]
I tried defining eq? and hash and uniq still fails. hash returns
identical values for objects with identical content and eq? returns
true in this case, but uniq does not remove them.
Probably the right thing to do is to write a couple of loops.
Jeff Nyman wrote:
> "gaspode" <stephendl@gmail.com> wrote in message
> news: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:
>
> <code>
> class RuleList
> def initialize
> @rules = Array.new
> end
>
> def append(this_rule)
> @rules.push(this_rule)
> end
>
> def selection
> @rules.find_all { |rule| rule }
> end
> end
> </code>
>
> Then I have a Rule class like this:
>
> <code>
> class Rule
> attr_accessor :point, :filter, :value
>
> def initialize(point, filter, value)
> @point = point
> @filter = filter
> @value = value
> end
>
> def to_s
> "#@point, #@filter, #@value"
> end
> end
> </code>
>
> 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?
>
> - Jeff