From: Phrogz Date: 2010-03-20T21:41:42+09:00 Subject: Re: problem making an array of arrays (of arrays) On Mar 18, 6:26 pm, Cec Tre wrote: > So, here is my problem. I want to create a 5x5 grid, however, each of > the 'cells' in the grid should be able to hold a variety of values. rb(main):001:0> a = Array.new(5){ Array.new(5) } => [[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]] irb(main):002:0> require 'pp'; pp a [[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 That says: Create an array with 5 elements; for each of the five elements, call this block and use the return value for the value of the element. When you call the block, create a new array of 5 empty elements. You also can use the index of the array in your block. For example: irb(main):009:0> CHARS = ('A'..'Z').to_a => ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] irb(main):010:0> excel = Array.new(5){ |row| Array.new(5){ |col| "#{CHARS[col]}#{row+1}" } } => [["A1", "B1", "C1", "D1", "E1"], ["A2", "B2", "C2", "D2", "E2"], ["A3", "B3", "C3", "D3", "E3"], ["A4", "B4", "C4", "D4", "E4"], ["A5", "B5", "C5", "D5", "E5"]] irb(main):012:0> pp excel [["A1", "B1", "C1", "D1", "E1"], ["A2", "B2", "C2", "D2", "E2"], ["A3", "B3", "C3", "D3", "E3"], ["A4", "B4", "C4", "D4", "E4"], ["A5", "B5", "C5", "D5", "E5"]] => nil > So, the solution I really want is: > > Is it possible to have a variable called, say... cellxx ... Then, some > piece of code that alters the xx part of the actual variable name > itself? That's a bad solution. Programmatically create or modify your array in loops; don't create explicit temporary variables you don't need. Here's another solution: irb(main):013:0> a = [] => [] irb(main):014:0> 5.times{ |i| a[i] = [] } => 5 irb(main):015:0> a => [[], [], [], [], []] irb(main):016:0> a[2][3] = "hi" => "hi" irb(main):017:0> a => [[], [], [nil, nil, nil, "hi"], [], []]