0

Context: Im trying to populate a 2D array with while loops ,after witch I want to try and do it with {} block format. The point is to understand how these two syntax structures can do the same thing.

I have been reviewing this code and scouring the internet for the past hour and Ive decided that I'm simply not getting something, but I dont understand what that is.

The outcome should be

=> [["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8"]
=> ..(Sequentially)..
=>["H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8"]]

The code is as follows:

char= ('A'..'H').to_a
num= (1..8).to_a
arr=Array.new(8,Array.new(8))

x=0
while x <8
  y=0
    while y < 8
    arr[x][y] = char[x] + num[y].to_s 
    y+=1
    end
  x+=1
end
arr

Thank you in advance, I appreciate your patience and time.

                                    ####Edit####

The source of the confusion was due to a lack of understanding of the reference concept. Referencing allows us, by using the Array.new(n,Array.new(n)) method scheme, to access the values of the nested arrays that share a reference to their data via their parent array. This question is addressed directly here: Creating matrix with `Array.new(n, Array.new)` . Although I thought it was a issue with my while loops, the problem was indeed how I created the matrix.

Abid
  • 270
  • 8
  • 18
  • 3
    Executive Summary: You almost never way to say `Array.new(8, Array.new(8))` because you'll end up sharing references, you almost always want `Array.new(8) { Array.new(8) }` instead so that the inner arrays are distinct arrays. – mu is too short Jan 02 '18 at 04:54

1 Answers1

0

Your code is not working due to call to reference. Ruby is pass-by-value, but all the values are references. https://stackoverflow.com/a/1872159/3759158 Have a look at the output

2.4.3 :087 > arr = Array.new(8,Array.new(8))
 => [[nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil]] 
2.4.3 :088 > arr[0][0] = 'B'
 => "B" 
2.4.3 :089 > arr
 => [["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil]] 

This is happen because of call by object on array object you can see this in effect by a simple example

a = []
b = a
b << 10
puts a => [10]

and very same thing is happening with your code.

Instead of all that try this :

('A'..'H').map{|alph| (1..8).map{|num| "#{alph}#{num}"}}
Manishh
  • 1,444
  • 13
  • 23