2009-12-13 89 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類對象,以便我可以進行比較?

乾杯

+0

這有點http://StackOverflow.Com/questions/1830420/ – 2009-12-13 11:56:26

+0

我提供了一個非常詳細的回答這個特定問題在這裏重複的:HTTP: //StackOverflow.Com/questions/1830420/is-it-possible-to-compare-private-attributes-in-ruby/1832634/#1832634。它也適用於你的問題。 – 2009-12-13 11:58:54

+0

在ruby中,比較兩個對象的方法通常命名爲'=='而不是'equal'' – johannes 2009-12-13 13:01:44

回答

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'就足夠了。 – 2009-12-13 12:00:03