I am working on a small rails app and have a problem with ruby's OOP model. I have the following simplified class structure.
class Foo
protected
@bar = []
def self.add_bar(val)
@bar += val
end
def self.get_bar
@bar
end
end
class Baz < Foo
add_bar ["a", "b", "c"]
end
My problem is now, that when I call add_bar in the class definition of Baz, @bar
is apparently not initialized and I get an error that the +
Operator is not available for nil
. Calling add_bar
on Foo
directly does not yield this problem. Why is that and how can I initialize @bar
correctly?
To make clear what I want, I will point out the behavior I would expect from these classes.
Foo.add_bar ["a", "b"]
Baz.add_bar ["1", "2"]
Foo.get_bar # => ["a", "b"]
Baz.get_bar # => ["a", "b", "1", "2"]
How could I achieve this?