You don't need an @array instance variable when subclassing Array – each instance already is an array.
Assuming that you are trying to implement a two-dimensional array on top of the build-in (one-dimensional) Array, something like this should work:
class CustomArray < Array
def initialize(rows, cols)
@rows = rows
@cols = cols
super(rows * cols)
end
def []=(row, col, value)
super(row * @rows + col, value)
end
def [](row, col)
super(row * @rows + col)
end
end
However, Ruby's core classes are heavily optimized and subclassing them can be quite tricky (see https://words.steveklabnik.com/beware-subclassing-ruby-core-classes).
Therefore, it's usually easier to use composition instead of inheritance, i.e. do use an @array instance variable, but don't inherit from Array, e.g.:
class CustomArray
def initialize(rows, cols)
@rows = rows
@cols = cols
@array = Array.new(rows * cols)
end
def []=(row, col, value)
@array[row * @rows + col] = value
end
def [](row, col)
@array[row * @rows + col]
end
end
[]=method?", but you already know the answer - you've done it in the code sample. Then to talk about instantiating a new class instance... What does this mean, exactly? Can you provide an example of where you are creating a new instance, and explain what behaviour you'd like/expect? And then you talk about "replacing the value ofself"... For a start, that's not possible (an object cannot change which object it is!) - but again, I don't really know what you mean since there's no code sample or explanation.