0

我正在尝试创建一个名为 Musician 的类,它继承自我的 Person 类,然后添加一个乐器属性。我知道我的 Musician 课程是错误的,但我只是想知道 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

谢谢您的帮助!

4

2 回答 2

1

如果您希望在 Musician 中使用 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在父类内部调用同名方法。

更新

我会把重点带回家。在这种完全虚构的情况下,您也可以使用 super :

class GuitarPlayer < Person
  attr_reader :instrument

  def initialize(first_name, last_name, age)
    super(first_name, last_name, age)
    @instrument = 'guitar'
  end
end

我们没有更改要初始化的参数,但我们已经扩展了行为。

于 2012-06-19T00:35:32.960 回答
0

That is the format for extending a class.

The problem is that you're calling the Musician initializer with more attributes than it accepts.

The error message you get states this pretty explicitly. When reporting or asking for help regarding an error, the error message you get should be shared so we don't have to guess or run your program.

You have at least options:

  • Give Musician an initialize that takes all the params, grabs instrument, and passes the rest.
  • Use Rails' Hash-based initialize (or roll your own, but you tagged it with rails).
于 2012-06-19T00:33:46.897 回答