From: Josh Cheek Date: 2010-11-08T17:52:01+09:00 Subject: Re: Don't work an array --20cf300fa9e9b3d38b049486bcc6 Content-Type: text/plain; charset=ISO-8859-1 On Sun, Nov 7, 2010 at 5:00 PM, Misha Ognev wrote: > Hello, this don't work on ruby 1.9.2. What's matter? > > $a = Array.new > for i in 1..5 > for j in 1..8 > $a[i][j] = i*j > end > end > > -- > Posted via http://www.ruby-forum.com/. > > The problem is that you haven't initialized the indexes you are accessing. $a = Array.new for i in 1..5 $a[i] = Array.new # **initialize** for j in 1..8 $a[i][j] = i*j end end Of course, you have several other issues as well. In Ruby, variables beginning with dollar signs are global. That is probably not what you wanted to do. To make it a local var, just don't use a sigil. a = Array.new # now it is local for i in 1..5 a[i] = Array.new for j in 1..8 a[i][j] = i*j end end You still have the issue that your array begins at 1, but Ruby arrays begin at zero. This means your first index is left nil. You can see what your object looks like by requiring the pp library, and passing a to the pp method. require 'pp' pp a # >> [nil, # >> [nil, 1, 2, 3, 4, 5, 6, 7, 8], # >> [nil, 2, 4, 6, 8, 10, 12, 14, 16], # >> [nil, 3, 6, 9, 12, 15, 18, 21, 24], # >> [nil, 4, 8, 12, 16, 20, 24, 28, 32], # >> [nil, 5, 10, 15, 20, 25, 30, 35, 40]] That probably isn't what you wanted. As stated by other users, check out the block form of Array.new require 'pp' a = Array.new 5 do |i| Array.new 8 do |j| i * j end end pp a # >> [[0, 0, 0, 0, 0, 0, 0, 0], # >> [0, 1, 2, 3, 4, 5, 6, 7], # >> [0, 2, 4, 6, 8, 10, 12, 14], # >> [0, 3, 6, 9, 12, 15, 18, 21], # >> [0, 4, 8, 12, 16, 20, 24, 28]] It looks like you might be coming from PHP or something. If that is the case, you should know that PHP's Arrays are sort of a hybrid between arrays and hash tables, filling both of those roles. In Ruby, they are different classes. But in Ruby 1.9.x, Hashes are ordered as in PHP (though they won't presume Array like indexing). --20cf300fa9e9b3d38b049486bcc6--