1

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! :)

8
  • Could you explain what you mean by "doesn't work"? It works fine for me. Commented Jan 23, 2015 at 15:55
  • check this stackoverflow.com/questions/1720932/… Commented Jan 23, 2015 at 15:56
  • Note that when using the same, unduplicated array (single) in all elements of the the double array, changing the contents of single in one row will change it in other rows as well (since it's really the same object). Commented Jan 23, 2015 at 15:58
  • i tried that on my irb console and it was working, what error are you getting. Commented Jan 23, 2015 at 15:59
  • I'm updating it! Thanks for the fast response. Commented Jan 23, 2015 at 15:59

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.