Accessing an instance variable of the parent class

How it works?

class A
  attr_accessor :name

  def initialize params
    @name = params[:name]
    @collection << B.new 
  end
end

class B < A
  def initialize
    @my_name = lookup_something(<parent.name>)
  end
end

Basically, I need a value from the parent class to use in searching the child class, but I don't want to pass it explicitly if there is a better way. Is the var instance of the parent completely inaccessible in the child class? Or is it just a bad hierarchy design?

+5
source share
3 answers

I really don't know what you are trying to do here - all the code you posted works with instance variables. Instance variables for each object, not for each class, so I don’t know what you mean when you say "I need a value from the parent class."

, :

  • . B A#initialize , .
  • B#initialize , A#initialize. . . , .
  • B.new('myname'), @name , A#initialize . super(:name => name) ( initialize), @name B#initialize
  • @name . , /.

, , , , , . , . , Ruby mixin, "" , , .

+8

John Nunemaker .

+3

What is the reason you want to Binherit from A? Unless you have another reason, the correct way to create it would be to simply take the name as a parameter for the constructor Band remove the inheritance.

class A
  attr_accessor :name

  def initialize params
    @name = params[:name]
    @collection << B.new(@name)
  end
end

class B
  def initialize name
    @my_name = lookup_something(@name)
  end
end
+2
source

All Articles