除了超类之外,我想创建一个子类来向子类添加属性。这就是我尝试过的:
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
class Musician < Person
attr_reader :first_name, :last_name, :age, :instrument
def initialize (first_name, last_name, age, instrument)
super
@instrument
end
end
class Person
ATTRS = ['first_name', 'last_name', 'age']
def attributes
ATTRS
end
end
class Musician < Person
ATTRS = ['instrument']
def attributes
super + ATTRS
end
end
这些都不奏效。
答案 0 :(得分:2)
在版本1中尝试
class Musician < Person
attr_reader :instrument
def initialize(first_name, last_name, age, instrument)
# Pass arguments to the super class' constructor!
super first_name, last_name, age
@instrument = instrument
end
end
感谢attr_reader :first_name, :last_name, :age
Person
中的Musician
因为继承而将拥有这三个访问者。