【问题标题】:Comparing two inherited objects Ruby比较两个继承的对象Ruby
【发布时间】:2009-12-13 10:39:10
【问题描述】:

我有一个包含相等的基类?方法。然后我继承了该对象并想使用等于?超类中的方法作为equal的一部分?子类中的方法。

    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 类对象进行比较?

干杯

【问题讨论】:

标签: ruby inheritance oop


【解决方案1】:
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)    

【讨论】:

  • super 不带参数提供与调用原始方法相同的参数。不需要显式调用super(other),直接调用super就够了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-21
  • 2021-12-13
  • 2011-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
相关资源
最近更新 更多