Dan Galipo
Dan Galipo

Reputation: 268

Comparing two inherited objects Ruby

I have a base class which contains an equal? method. I've then inherited that object and want to use the equal? method in the super class as part of the equal? method in the sub class.

    class A
       @a
       @b

    def equal?(in)
       if(@a == in.a && @b == in.b)
         true
       else
         false
       end
    end
end

class B < A
      @c
  def equal?(in)
   #This is the part im not sure of
     if(self.equal?in && @c == in.c)
       true
     else
       false
     end
   end
end

How do i reference the inherited A class object in the subclass so i can do the comparison?

Cheers

Dan

Upvotes: 0

Views: 233

Answers (1)

akuhn
akuhn

Reputation: 27793

class A
  attr_accessor :a, :b
  def equal? other
    a == other.a and b == other.b
  end
end

class B < A
  attr_accessor :c
  def equal? other
    # super(other) calls same method in superclass, no need to repeat 
    # the method name you might be used to from other languages.
    super(other) && c == other.c
  end
end

x = B.new
x.a = 1
y = B.new
y.a = 2
puts x.equal?(y)    

Upvotes: 3

Related Questions