Ocmer
Ocmer

Reputation: 245

Ruby change value in two dimensional array

I want to change a value of a two dimensional array.

This is the array:

class Test
    def initialize
        @single = [1,2,3,4,5,6,7,8,9,10]
        @double = [@single, @single, @single, @single]
    end
    def changeValue i, j
        @double[i][j] = nil
    end
    def showDouble
        return @double
    end
end

I want to change a value in the double array (the two dimensional array). If I want to change the value of 9 in the first array, then I should do something like this:

test = Test.new
test.changeValue 0, 8
puts test.showDouble

When I do this, then the value of 9 is in every array nil. I only want to change it in one array. Any help is welcome! :)

Upvotes: 1

Views: 691

Answers (2)

Rustam Gasanov
Rustam Gasanov

Reputation: 15781

Here

@double = [@single, @single, @single, @single]

you fill array with same object, in changeValue you change it, so it is being changed 4 times for @double. If you want 4 different objects, init @double as:

@double = [@single.dup, @single.dup, @single.dup, @single.dup]

Upvotes: 3

pjs
pjs

Reputation: 19855

The array @double actually contains four references to the same array @single, which is why you're getting the behavior you describe.

Initialize @double = [@single.clone, @single.clone, @single.clone, @single.clone] to get independent (but initially identical) sub-arrays.

Upvotes: 4

Related Questions