I would like to create a base class to handle all the methods. How would I achieve this using ruby in this scenario?
class Dog
def initialize
@breed = "good breed"
end
def show_dog
puts "#{self.class.first_name} of breed #{@breed}"
end
end
class Lab < Dog
attr_reader :first_name
def initialize
@first_name = "good dog"
end
end
lb = Lab.new()
lb.show_dog
The expected result would be "good dog of breed good breed" Thank you in advance :)
self.class.first_name
doesn't do what you probably wanted to do. You need to use @first_name
directly.
You need to call the parent class' constructor from the child class; it's not called automatically.
This works:
class Dog
def initialize
@breed = "good breed"
end
def show_dog
puts "#{@first_name} of breed #{@breed}" ### <- Changed
end
end
class Lab < Dog
attr_reader :first_name
def initialize
super ### <- Added
@first_name = "good dog"
end
end
lb = Lab.new()
lb.show_dog
self.class.first_name
means Lab.first_name
, not Lab's instance lb.first_name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With