How to declare a two-dimensional array in Ruby

I need a two-dimensional array in Ruby, which I can access, for example, as follows:

if @array[x][y] == "1" then @array[x][y] = "0" 

The problem is this: I do not know the initial sizes of the sizes of the array, and I grow the array (with the << operator).

How to declare it as an instance variable, so I am not getting any errors?

 undefined method `[]' for nil:NilClass (NoMethodError) 

UPDATED QUESTION:

 @array = Array.new {Array.new} 

now works for me, so the comment from Matt below is correct!

I just figured out the reason I got the error, because I repeated this array as follows:

 for i in 0..@array.length for j in 0..@array [0].length @array[i][j] ... 

which, obviously, was wrong and caused an error. It should be like this:

 for i in 0..@array.length-1 for j in 0..@array [0].length-1 @array[i][j] ... 
+7
source share
3 answers

A simple implementation for a sparse two-dimensional array using nested hashes,

 class SparseArray attr_reader :hash def initialize @hash = {} end def [](key) hash[key] ||= {} end def rows hash.length end alias_method :length, :rows end 

Using:

 sparse_array = SparseArray.new sparse_array[1][2] = 3 sparse_array[1][2] #=> 3 p sparse_array.hash #=> {1=>{2=>3}} # # dimensions # sparse_array.length #=> 1 sparse_array.rows #=> 1 sparse_array[0].length #=> 0 sparse_array[1].length #=> 1 
+7
source

Matt's comment on your question is absolutely correct. However, based on the fact that you marked this โ€œpipelined gameโ€, it looks like you are trying to initialize a two-dimensional array, and then use it in the calculations for the game. If you want to do this in Ruby, one way to do this is:

 a = Array.new(my_x_size) { |i| Array.new(my_y_size) { |i| 0 }} 

which will create an array my_x_size * my_y_size filled with zeros.

What this code does is to create a new array of your size x, and then initialize each element of this array as a different array of your size y and initialize every element of every second array with 0.

+5
source

Ruby Array does not provide you with this functionality.

Or you will do it manually:

 (@array[x] ||= [])[y] = 42 

Or do you use hashes:

 @hash = Hash.new{|h, k| h[k] = []} @hash[42][3] = 42 @hash # => {42 => [nil, nil, nil, 42]} 
+3
source

All Articles