0

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
  • This is sort of a duplicate of StackOverflow.Com/questions/1830420 Commented Dec 13, 2009 at 11:56
  • I provided a very detailed answer to that particular question here: StackOverflow.Com/questions/1830420/… . It also applies to your question. Commented Dec 13, 2009 at 11:58
  • in ruby the the method for comparing two object is usually named == and not equal? Commented Dec 13, 2009 at 13:01

1 Answer 1

3
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)    
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.