2009-12-13 7 views
0

나는 동등한 것을 포함하는 기본 클래스를 가지고 있습니까? 방법. 나는 그 객체를 물려 받았고 동등 물을 사용하고 싶습니까? 같은 클래스의 슈퍼 클래스에서의 메소드? 메서드를 호출합니다.상속 된 두 객체 비교하기 Ruby

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 

내가 비교할 수 있도록 하위 클래스의 상속 된 A 클래스 개체를 어떻게 참조합니까? HTTP :

건배

+0

이 내가 여기에 특정 질문에 대한 매우 상세한 답을 제공 http://StackOverflow.Com/questions/1830420/ –

+0

의 중복의 일종이다 : //StackOverflow.Com/questions/1830420/is-it-possible-to-compare-private-attributes-in-ruby/1832634/#1832634. 또한 귀하의 질문에 적용됩니다. –

+0

ruby에서 두 객체를 비교하는 메소드는 대개'=='로 지정되고'equal '이 아닙니다. – johannes

답변

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)  
+2

인수없이'super'는 원래 메소드가 호출 된 것과 같은 인수를 제공합니다. 명시 적으로'super (other)'를 호출 할 필요는 없으며 단지'super'만으로 충분합니다. –