I’m trying to create a class called Musician which inherits from my class Person and then adds an instrument attribute. I know my Musician class is wrong, but I just wanted to know what the correct format is in Ruby. Here is all of my code:
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
Thanks for the help!
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:supercalls 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:
We haven’t changed the arguments to initialize but we have extended the behavior.