0

クラスPersonを継承し、instrument属性を追加する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

If you want first_name, last_name and age to be available in Musician then you must include them in the initializer and take advantage of super. Something like:

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 calls the method with the same name inside of the parent class.

UPDATE

I will drive the point home. You would also use super in this totally made up situation:

class GuitarPlayer < Person
  attr_reader :instrument

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

We haven't changed the arguments to initialize but we have extended the behavior.

于 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 に答える