为什么第一个测试返回173,而不是81,而不是第二个测试,而不是9?如何从@cells.each_slice(9).map { |v| v }
-count
方法返回数组数?
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
我复制并将数字字符串粘贴到IRB中,并发现173来自以下位置:
irb(main):001:0> a = '01500300200010090627
irb(main):002:0' 00684304900020175010
irb(main):003:0' 40380003905000900081
irb(main):004:0' 04086007002503720460
irb(main):005:0' 0'
=> "01500300200010090627n 00684304900020175010n 40380003905000900081n 04086007002503720460n 0"
irb(main):006:0> a.length
=> 173
您可以看到它包括新线和空间。您可能想要这个:
let(:puzzle) { '01500300200010090627' +
'00684304900020175010' +
'40380003905000900081' +
'04086007002503720460' +
'0' }
关于 @rows
我猜你想要
@rows = @cells.each_slice(9).to_a
但是在您的测试中,您应该有
expect(grid.rows.size).to eq(9)
确实更改行
@cells = puzzle.chars.map { |x| (x.to_i) }
AS
@cells = puzzle.gsub(/[^0-9]/,'').chars.map { |x| (x.to_i) }
完整代码:
class Grid
attr_reader :cells
def initialize(puzzle)
@cells = puzzle.gsub(/[^0-9]/,'').chars.map { |x| (x.to_i) }
end
def rows
@rows = @cells.each_slice(9).map { |v| v }
end
end
s = '01500300200010090627
00684304900020175010
40380003905000900081
04086007002503720460
0'
grid = Grid.new(s)
grid.cells.length # => 81
grid.rows.size # => 9