Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get child class variable back into parent class in ruby

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 :)

like image 584
Quentin Avatar asked Jan 13 '23 19:01

Quentin


2 Answers

  1. self.class.first_name doesn't do what you probably wanted to do. You need to use @first_name directly.

  2. 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
like image 164
Dogbert Avatar answered Jan 20 '23 23:01

Dogbert


self.class.first_name means Lab.first_name, not Lab's instance lb.first_name

like image 30
akostrikov Avatar answered Jan 20 '23 21:01

akostrikov