0

I'm making a game with a Board class Cell class. The Board class needs to be initialized with a unique instance variable for each Cell. I can hardcode it so that it works, but it seems inelegant and doesn't allow the size of the board to be chosen by the user at runtime. Here's what I have:

class Board
  def initialize
    @cell_1 = Cell.new(1)
    @cell_2 = Cell.new(2)
    @cell_3 = Cell.new(3)
    @cell_4 = Cell.new(4)
    @cell_5 = Cell.new(5)
    @cell_6 = Cell.new(6)
    @cell_7 = Cell.new(7)
    @cell_8 = Cell.new(8)
    @cell_9 = Cell.new(0)
    @cells = [@cell_1, @cell_2, @cell_3,
              @cell_4, @cell_5, @cell_6,
              @cell_7, @cell_8, @cell_9]
  end
end

I think I could use a loop to create a hash with unique key names pointing to unique Cell objects, but I don't know how I could make unique instance variables with a loop.

2 Answers 2

1

If you don't need to create each instance variables (@cell_1, @cell_2, ...), you can use Enumerable#map:

@cells = [*1..8, 0].map { |i| Cell.new(i) }
Sign up to request clarification or add additional context in comments.

1 Comment

I actually had been referring to each instance variable by their names and for some reason thought I needed to. It turns out I didn't. When I tried this and then switched the references (eg. @cells[0] instead of @cell_1), it worked. Thanks for your help.
0

If you really need to refer every instance variable by name you can do something like this.

class Board
   def initialize
     @cells = (1..9).to_a.map { |i| Cell.new(i) }
   end

   def method_missing(method, *args, &block)
     if method =~ /^cell_[1-9][0-9]*$/
       index = method[/\d+/].to_i
       @cells[index-1]
     else
       super
     end
   end
end

In this way you can call:

board = Board.new
board.cell_1 #=> first cell

Of course I'd use the solution proposed by @falsetru.

Comments

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.