Battleship [] and []=

Hi Everyone, I am having some trouble with the [] and []= methods, so far all of my tests are passing except for attack and place_random_ship and are failing because of [] and []=
I’ll post them below, I’d appreciate it if anyone can tell me what I did wrong.

def attack(position)
    # debugger
    if @board.empty?(position)
      @board.grid[position.first][position.last] = :x

 def [](pos)
    x, y = [pos]

  def []=(pos, val)
    x, y = [pos]
    @grid[x][y] = val

Can you show me your errors please?


  1. BattleshipGame#attack marks the board at the specified position
    Failure/Error: expect(game.board[[1, 1]]).to eq(:x)
    no implicit conversion of Array into Integer

    ./lib/board.rb:55:in `[]’

    ./lib/board.rb:55:in `[]’

    ./spec/battleship_spec.rb:24:in `block (3 levels) in <top (required)>’

  2. Board#place_random_ship when the board is empty places a ship in a random position
    Failure/Error: empty_board.place_random_ship
    Board is full

    ./lib/board.rb:50:in `place_random_ship’

    ./spec/board_spec.rb:103:in `block (4 levels) in <top (required)>’

  3. Board#place_random_ship when the board is empty places ships until the board is full
    Failure/Error: expect do
    expected no Exception, got #<RuntimeError: Board is full> with backtrace:
    # ./lib/board.rb:50:in place_random_ship' # ./spec/board_spec.rb:110:inblock (5 levels) in <top (required)>’
    # ./spec/board_spec.rb:109:in `block (4 levels) in <top (required)>’

    ./spec/board_spec.rb:109:in `block (4 levels) in <top (required)>’

x, y = [pos]

First of all, I believe you need to get rid of the brackets around pos in the second line of the above method. Pos is already an array.

yes, that fixed it! Thank you! I can’t believe I missed that… :confused: