views:

26

answers:

1

Hi,

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

+3  A: 
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)
Adrian
`super` without arguments supplies the same arguments as the original method was called with. There is not need to explicitly call `super(other)`, just plain `super` is enough.
Jörg W Mittag