【问题标题】:Ruby SuperclassesRuby 超类
【发布时间】:2014-11-25 18:01:29
【问题描述】:

下面的节目是试图接纳一位美国总统、法国总统的年龄和姓名。问题是法国总统在说出他的名字、年龄和公民身份后会说“bein sur”(不是我的想法)。我对这位法国总统的标语有意见。这是我的代码

class President
  attr_accessor :name, :age

  def initialize(name, age)
     @name = name 
     @age = age
  end 

  def name=(name) # setter
   @name = name
  end

  def name # getter
   @name
  end

  def age=(age)
   @age = age
  end

  def age
   @age
  end
end

class FrancePresident < President
  def self.citizenship
    "La France"
  end 

  def initialize(name, age)
    super(name)
    super(age)
  end 

  def catchphrase
    "bein sur"
  end

end

class UnitedStatesPresident < President
  def self.citizenship
    "The Unites States of America"
  end
end

我为他的流行语使用的实例方法是许多人中最后一次尝试让这个人说出这个短语,但它不完整,我想我应该定义对超类的调用以获取他的名字和年龄,但我不确定如何克服这个参数错误。

ArgumentError
wrong number of arguments (1 for 2)
exercise.rb:4:in `initialize'

exercise.rb:32:in `initialize'

exercise_spec.rb:24:in `new'

exercise_spec.rb:24:in `block (3 levels) in <top (required)>'

我是 ruby​​ 的新手,所以任何提示或建议将不胜感激。

【问题讨论】:

  • 你的def age/def age=()(和name也是)是多余的,因为attr_accessor :name, :age自动定义那些其他方法正是attr_accessor完成的,所以你不需要自己定义它们.
  • 哦,所以attr_accessor 就像一个内置的getter 和setter?
  • 标语应为“bien sûr” :) 来源:translate.google.com/#en/fr/of%20course
  • @ClydeBrown 是的,它是定义您定义的确切简单 getter/setter 的简写。如果您必须在 setter 或 getter 中做更多工作(例如验证),您需要自己定义它们,但 attr_accessor 会生成您为 getter/setter 包含的代码。
  • @ClydeBrown 如果您在这些对象上调用attr_accessor,然后调用President.new.methods,您会在其可用的实例方法中找到age, age=, name, name=

标签: ruby-on-rails ruby superclass


【解决方案1】:

替换这个:

super(name)
super(age)

用这个:

super(name, age)

President 中的initialize 方法采用两个 参数,而不是一个。

你甚至可以去掉参数,默认情况下会传递参数:

super

更好的是,只需删除President 的子类中的整个initalize 方法,因为它是继承的。

【讨论】:

  • 或者,完全省略参数(name,age),只调用super,传递给子类初始化器的相同参数将传递给超类。
  • @MichaelBerkowski 刚刚意识到整个initialize 方法可以在子类中省略。
  • 到八月:President中的initialize方法有两个参数,不是一个。所以两个参数都需要在同一个super()中?为什么?
  • 致 Michael 和 August:为什么在子类中省略初始化?
  • @ClydeBrown 因为它就像任何其他方法一样。调用foo(1),然后foo(2)等同于foo(1, 2)。您可以在子类中省略 initialize,因为它是从超类继承的。阅读关于继承here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-04
  • 2021-06-17
  • 2013-10-28
相关资源
最近更新 更多