whatyouhide
whatyouhide

Reputation: 16801

Ruby - inheriting from Array

I'm pretty new to Ruby. I need to extend Array and I need my class to represent bidimensional arrays.

I've done this:

class MyExtension < Array

    def initialize(n)
        super(n, Array.new(n, nil))
        self[0][0] = "hello"
    end

end

This looks theoretically right to me, but when I do:

p MyExtension.new(2)

I get

[["hello", nil], ["hello", nil]]

instead of the expected:

[["hello", nil], [nil, nil]]

What am I getting wrong?

Upvotes: 3

Views: 1284

Answers (1)

sawa
sawa

Reputation: 168269

That is a common mistake a beginner often makes. If you do super(n, Array.new(n, nil)), then Array.new(n, nil) will be evaluated only once, giving that same array (same object id) for each row. Since all the rows would be repetition of the same array, modifying one row by self[0][0] = "hello" would change all the other rows.

Instead, do

class MyExtension < Array
  def initialize(n)
    super(n){Array.new(n, nil)}
    self[0][0] = "hello"
  end
end

MyExtension.new(2) # => [["hello", nil], [nil, nil]]

Upvotes: 11

Related Questions