How to create a 2D array of objects in Ruby?

6.9k Views Asked by At

I am creating a map for my roguelike game and already I stumbled on a problem. I want to create a two dimensional array of objects. In my previous C++ game I did this:

class tile; //found in another file.

tile theMap[MAP_WIDTH][MAP_HEIGHT];

I can't figure out how I should do this with Ruby.

4

There are 4 best solutions below

3
On
theMap = Array.new(MAP_HEIGHT) { Array.new(MAP_WIDTH) { Tile.new } }
5
On

Use arrays of arrays.

board = [
 [ 1, 2, 3 ],
 [ 4, 5, 6 ]
]

x = Array.new(3){|i| Array.new(3){|j| i+j}}

Also look into the Matrix class:

require 'matrix'
Matrix.build(3,3){|i, j| i+j}
0
On

2D arrays are no sweat

array = [[1,2],[3,4],[5,6]]
 => [[1, 2], [3, 4], [5, 6]] 
array[0][0]
 => 1 
array.flatten
 => [1, 2, 3, 4, 5, 6] 
array.transpose
 => [[1, 3, 5], [2, 4, 6]] 

For loading 2D arrays try something like:

rows, cols = 2,3
mat = Array.new(rows) { Array.new(cols) }
0
On
# Let's define some class
class Foo
  # constructor
  def initialize(smthng)
    @print_me = smthng
  end
  def print
    puts @print_me
  end
# Now let's create 2×2 array with Foo objects
the_map = [
[Foo.new("Dark"), Foo.new("side")],
[Foo.new("of the"), Foo.new("spoon")] ]

# Now to call one of the object's methods just do something like
the_map[0][0].print # will print "Dark"
the_map[1][1].print # will print "spoon"