0

I have this parent class:

class ListBase
  @@list = []

  def self.list
    @@list
  end
end

I'm trying to create two child classes like so:

class Child1 < ListBase
end

class Child2 < ListBase
end

I was under the impression that each of these child classes will have their own @@list class variable. However, I get this:

Child1.list.push(1)
Child2.list.push(2)
Child1.list # => [1, 2]
Child2.list # => [1, 2]

which means the child classes share the @@list from the parent class.

How can I create a separate class variable for each of the child classes without repeating?

sawa
  • 165,429
  • 45
  • 277
  • 381
Ashish Acharya
  • 3,349
  • 1
  • 16
  • 25
  • Check: https://stackoverflow.com/questions/1251352/ruby-inherit-code-that-works-with-class-variables – Marcin Kołodziej Nov 09 '18 at 04:39
  • 1
    I'm curious why you want to do that. Class *instance* variables are typically used for what you describe, as their scope is confined to the class in which they are created. – Cary Swoveland Nov 09 '18 at 05:30
  • Actually, your question "How can I create a separate class variable for each of the child classes without repeating?" is contradictory. A class variable is **for sharing** among the child classes, and you are trying not to share it. – sawa Nov 09 '18 at 08:34

2 Answers2

1

You are using class variable through class method (getter/reader).
So you can override that method in derived classes and use own class variable for every derived class.
Not fun, but that how class variables works, they are shared within a class and derived classes as well.

class ListBase
  def self.list
    @@base_list ||= []
  end
end

class ListOne
  def self.list
    @@one_list ||= []
  end
end

class ListTwo
  def self.list
    @@two_list ||= []
  end
end

ListOne.list << 1
ListTwo.list << 2

puts ListOne.list
# => [1]
puts ListTwo.list
# => [2]
Fabio
  • 31,528
  • 4
  • 33
  • 72
1

As @CarySwoveland comments, in your use case, you should use a class instance variable:

class ListBase
  @list = []

  def self.list
    @list
  end
end

Not even sure why you thought of using a class variable for your use case.

sawa
  • 165,429
  • 45
  • 277
  • 381