爲什麼第一次測試返回173,而不是81,第二個20,而不是9?我如何從@cells.each_slice(9).map { |v| v }
- count
方法返回數組的數量?Sudoku解決方案的開始:2個rspec失敗
class Grid
attr_reader :cells
def initialize(puzzle)
@cells = puzzle.chars.map { |x| (x.to_i) }
end
def rows
@rows = @cells.each_slice(9).map { |v| v }
end
end
規範
require 'Grid'
describe Grid do
context "initialization" do
let(:puzzle) { '01500300200010090627
00684304900020175010
40380003905000900081
04086007002503720460
0'}
let(:grid) { Grid.new(puzzle) }
it 'should have 81 cells' do
expect(grid.cells.length).to eq(81)
end
it 'should have an unsolved first cell' do
expect(grid.cells.first).to eq(0)
end
it 'should have 9 rows' do
expect(grid.rows).to eq(9)
end
end
end
rspec的報告
Grid
initialization
should have 81 cells (FAILED - 1)
should have an unsolved first cell
should have 9 rows (FAILED - 2)
Failures:
1) Grid initialization should have 81 cells
Failure/Error: expect(grid.cells.length).to eq(81)
expected: 81
got: 173
(compared using ==)
# ./spec/grid_spec.rb:14:in `block (3 levels) in <top (required)>'
2) Grid initialization should have 9 rows
Failure/Error: expect(grid.rows).to eq(9)
expected: 9
got: 20
(compared using ==)
# ./spec/grid_spec.rb:22:in `block (3 levels) in <top (required)>'
Finished in 0.00165 seconds
3 examples, 2 failures
感謝。任何想法如何我可以返回'@rows = @ cells.each_slice(9).map {| v | v}'? – HandDisco
@Abraham回答更新以解決此問題。 – Matt
當然! 'to_a' then'.count' return 9.我過於複雜了。謝謝。 – HandDisco