4

我正在编写一个程序,其中一个类与另一个类具有相同的行为。唯一的区别是有一个类变量 ,@secret_num它在两个类之间的计算方式不同。我想调用一个特定的超类方法,但使用子类中的类变量。棘手的是类变量不是常量,所以我在它自己的方法中设置它。有什么办法可以做我在下面尝试做的事情吗?谢谢

Class Foo
  def secret
    return [1,2,3].sample
  end

  def b
    @secret_num = secret
    ... # lots of lines of code that use @secret_num
  end
end

Class Bar < Foo
  def secret
    return [4, 5, 6].sample
  end

  def b
    super    # use @secret_num from class Bar.
  end
end    

这不起作用,因为调用super也调用了父类的secret方法, ie Foo#secret,但我需要使用子类的秘密号码, ie Bar#secret

4

1 回答 1

4
class Foo
  def secret
    [1,2,3].sample
  end

  def b(secret_num = secret)
    <lots of lines of code that use secret_num>
  end
end

class Bar < Foo
  def secret
    [4, 5, 6].sample
  end
end    

请注意,您不需要secret作为参数传递给b. 只要您不在b子类中重新定义,继承就会负责调用secret.

我的偏好是将它作为参数,以便我可以在测试中传递各种值。

于 2012-09-18T14:01:25.023 回答