Ruby,无法将fixnum转换为数组?但它是一个数组

时间:2011-01-29 09:06:48

标签: ruby-on-rails

boardwidth是3

我用1x9数组代表一个3x3矩阵

测试:

  test "the row checking to see if we have a winner (incorrect)" do
    board = Board.new

    board.state = [0,0,1,0,0,1,0,0,1]
    assert false ==board.check_rows_for_winner
  end

相关代码

  @board_layout = []

 def init_board
    @board_layout = Array.new(@@board_width * @@board_width)
  end

  def state=(custom_board)
    @board_layout = custom_board
  end


def check_rows_for_winner
  self.width.times do |row|
    if @board_layout.transpose[row].uniq.size == 1 then 
      return true
    end
  end

  return false
end

错误:

TypeError: can't convert Fixnum into Array
    app/models/board.rb:39:in `transpose'
    app/models/board.rb:39:in `check_rows_for_winner'
    app/models/board.rb:38:in `times'
    app/models/board.rb:38:in `check_rows_for_winner'

1 个答案:

答案 0 :(得分:2)

为了使用@ array.tranpose,你的@array需要是数组数组。使用普通数组,您会收到此错误消息。

编辑:

在测试中,您要为@board_layout设置以下内容:

 board.state = [0,0,1,0,0,1,0,0,1]

当你做

@board_layout.transpose[row]

您将收到错误消息。