0

Decided to make a method for creating two-dimensional array. The array looks well, but when I'm trying to change the value, I change that value in all the sub-arrays, so it looks like this:

a[0][0] = 0

[[0, "", ""], [0, "", ""], [0, "", ""]]

Any ideas how to make it work properly?

Here's the method for creating the array:

def create_array(size)
array = []
line = []
size.times { line << "*" }
size.times { array << line }
array
end
3
  • Your create_array puts the same line in each row of your 2D array. And what's size? Is it a square matrix, with size rows and size columns? Commented Feb 16, 2015 at 21:07
  • @lurker Yes, that's what I need. But when I modify the array, I change values in all lines, but I want to change the value only in one line. Yes, that's that square matrix Commented Feb 16, 2015 at 21:10
  • Like I said, each line is the same line. It's the same array object in each row of array. So when you change one, you've changed them all. Commented Feb 16, 2015 at 21:15

1 Answer 1

1

This code puts the same line in each row of array:

def create_array(size)
  array = []                # Create an Array object, "array"
  line = []                 # Create an Array object, "line"

  size.times { line << "*" }

  # The following line puts the SAME Array object, "line", into
  # array "size" times
  #
  size.times { array << line }
  array
end

You need to put a new one in each time. I assume by size you mean that's a square matrix:

def create_array(size)
  Array.new(size) { Array.new(size, "*") }
end

Here, Array.new(n, elt) creates a new Array object of length n and filled with element, elt. See Ruby Array "new" method. Note that trying to do something like this has a similar issue as the original problem:

Array.new(size, Array.new(size, "*"))

In this case, Array.new(size, "*") occurs once and as passed as the second argument to the "outer" Array.new(size, ...), so each row here is also the same Array object. Passing the block to Array.new(...) as above generates a separate Array.new(size, "*") call for each row.

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

1 Comment

Thank tou so much! Now I understand that I need to create new array each time rather than using the same object

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.