Ruby - 如何填充二维数组?

时间:2014-01-01 13:37:43

标签: ruby arrays rspec multidimensional-array

我有这个rspec测试:

  it 'has a populated chessboard' do
    expect(ChessBoard.new.populate_new_board).to eq [
      ['pawn','pawn','pawn','pawn','pawn','pawn','pawn','pawn'],
      ['pawn','pawn','pawn','pawn','pawn','pawn','pawn','pawn'],
      ['pawn','pawn','pawn','pawn','pawn','pawn','pawn','pawn'],
      ['pawn','pawn','pawn','pawn','pawn','pawn','pawn','pawn'],
      ['pawn','pawn','pawn','pawn','pawn','pawn','pawn','pawn'],
      ['pawn','pawn','pawn','pawn','pawn','pawn','pawn','pawn'],
      ['pawn','pawn','pawn','pawn','pawn','pawn','pawn','pawn'],
      ['pawn','pawn','pawn','pawn','pawn','pawn','pawn','pawn']]

  end

对于此代码:

class ChessBoard

  def initialize
    @board=Array.new(7){Array.new(7)}
  end

  def populate_new_board
    (0..7).each do |row|
      (0..7).each do |cell|
        @board[row][cell]='pawn'
      end
    end
    @board
  end

end

但我得到了:

  1) least number of moves from x to y has a populated chessboard
     Failure/Error: expect(ChessBoard.new.populate_new_board).to eq [
     NoMethodError:
       undefined method `[]=' for nil:NilClass
     # ./code.rb:10:in `block (2 levels) in populate_new_board'
     # ./code.rb:9:in `each'
     # ./code.rb:9:in `block in populate_new_board'
     # ./code.rb:8:in `each'
     # ./code.rb:8:in `populate_new_board'
     # ./code_spec.rb:12:in `block (2 levels) in <top (required)>'

我该如何解决这个问题?

btw每个空间的棋子都不是最终的结果,但这就是我现在想要的这个测试(然后我可以进一步修改它)。

3 个答案:

答案 0 :(得分:2)

class ChessBoard
   def populate_new_board
      @board = [['pawn'] * 7] * 7
   end
end

答案 1 :(得分:1)

将其更改为:

def populate_new_board
  (0...7).each do |row|
    (0...7).each do |cell|
      @board[row][cell]='pawn'
    end
  end
  @board
end

答案 2 :(得分:0)

因为有人表示你在范围内犯了一个错误,但强烈建议你减少索引范围的使用。您可以改为使用:each:map方法:

class ChessBoard
   def initialize
      @board = Array.new( 7 ){ Array.new( 7 ) }
   end

   def populate_new_board
      @board.each {| row | row.map! {| _ | 'pawn' } }
   end
end

但我会使用更多简单的代码:

class ChessBoard
   def populate_new_board
      @board = Array.new( 7 ){Array.new( 7 ) { 'pawn' } }
   end
end