Reputation: 197
I am building a Chess program in Ruby and my Square objects are in a multi-dimensional array.
class Square
attr_accessor :piece_on_square, :x, :y, :coordinates
def initialize(piece_on_square=nil, x=nil, y=nil, coordinates=nil)
@piece_on_square = piece_on_square
@x = x
@y = y
@coordinates = coordinates
end
end
@square_array = Array.new(8){Array.new(8){Square.new}}
The problem comes when I try to select a Square object in the @square_array
which matches a condition (such as a Square with coordinates
of "a4"
). I've tried using nested #each_with_index
calls with #select
but that isn't working. I've only been able to select the array itself, not the object in the array. What's the best way to do this?
Upvotes: 0
Views: 662
Reputation: 168249
I see many people building nested arrays for doing this kind of thing, encountering various problems that stem from using nested arrays. The obvious solution is: get rid of nested arrays, and use a flat array.
If I were to do such programming, I would use a flat array, and do row/column operations using the array index and modulo operations (Fixnum#%
for columns, Fixnum#/
for rows).
But in your case, you seem to be saving the column and row numbers, and even the coordinate name, for each square, so it is easier for you to use a flat hash with either the row-column combination or the coordinate name as the key.
Upvotes: 3