0

I am building a Chess program in Ruby and my Square objects are in a multi-dimensional array.

Example code for Square class:

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 

Code within my Board class:

@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?

2
  • Create some example with values in square and explain what exactly you want to achieve ? Commented Dec 3, 2015 at 14:15
  • FYI: In Ruby, you don't have to pre-create the array the way you do it in Java or C++. This code will perfectly fine - arr = [];arr[10] = "Hi";p arr Commented Dec 3, 2015 at 14:32

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Originally I actually had a flat array but changed it to a 2d array because I thought it is more OO (a board is an 8x8 grid, not 64 spaces) and would be easier when I wanted to display the board. However, you're right, because I'm keeping track of x and y values in addition to the coordinate name, it may be easier in the long run to move it back to a flat array
@scobo Do you think a row in a chess board has any reality/significance to be modeled as an object, (while leaving aside the columns)? I don't think so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.