创建一个inheritance自Ruby中另一个类的类

我正在尝试创建一个名为Musician的类,它inheritance自我的类Person,然后添加一个instrument属性。 我知道我的音乐家课是错的,但我只是想知道Ruby中正确的格式是什么。 这是我的所有代码:

class Person attr_reader :first_name, :last_name, :age def initialize (first_name, last_name, age) @first_name = first_name @last_name = last_name @age = age end end p = Person.new("Earl", "Rubens-Watts", 2) p.first_name p.last_name p.age class Musician < Person attr_reader :instrument def initialize (instrument) @instrument = instrument end end m = Musician.new("George", "Harrison", 58, "guitar") m.first_name + " " + m.last_name + ": " + m.age.to_s m.instrument 

谢谢您的帮助!

如果你想在音乐家中使用first_name,last_name和age,那么你必须将它们包含在初始化器中并利用super 。 就像是:

 class Musician < Person attr_reader :instrument def initialize(first_name, last_name, age, instrument) super(first_name, last_name, age) @instrument = instrument end end 

super在父类中调用具有相同名称的方法。

UPDATE

我会把重点放在家里。 在完全构成的情况下你也会使用super:

 class GuitarPlayer < Person attr_reader :instrument def initialize(first_name, last_name, age) super(first_name, last_name, age) @instrument = 'guitar' end end 

我们没有改变初始化的参数,但我们扩展了行为。

这是扩展类的格式。

问题是你正在使用比它接受的更多属性调用Musician初始化程序。

您得到的错误消息明确说明了这一点。 在报告或寻求有关错误的帮助时,应该共享您收到的错误消息,这样我们就不必猜测或运行您的程序。

你至少有选择:

  • Musician一个initialize ,它接受所有参数,抓取乐器,然后传递其余的。
  • 使用Rails的基于哈希的initialize (或者自己滚动,但是用rails标记它)。