我已接近解决这一挑战,但是,我无法弄清楚如何重构我的代码以使以下规范通过。
要传递的规范:
Test.assert_equals(checkered_board(2), "\u25A1 \u25A0\n\u25A0 \u25A1")
我的错误:
Expected: "\u25A1 \u25A0\n\u25A0 \u25A1", instead got: "\u25A1 \u25A0 \n\u25A0 \u25A1 "
我的尝试(通过视觉上的repl.it,一切看似正确)
def checkered_board(dimension)
return false unless dimension.integer? && dimension >= 2
checkboard = nil
checker_array = []
count = dimension
while dimension % 2 == 0 && count > 0 # set-up for even number passed in
if count % 2 == 0
checkboard = ("\u25A1 \u25A0 ") * (dimension / 2)
checkboard += "\n"
checker_array << checkboard
count -= 1
else
checkboard = ("\u25A0 \u25A1 ") * (dimension / 2)
if count == 1 #if count is the last number before 0, do not add \n to pass spec
checker_array << checkboard
else
checkboard += "\n"
checker_array << checkboard
end
count -= 1
end
end
while dimension % 2 == 1 && count > 0 # set-up for odd number passed in
if count % 2 == 1
checkboard = ("\u25A0 \u25A1 ") * (dimension / 2)
checkboard += "\u25A0"
if count == 1 #if count is the last number before 0, do not add \n to pass spec
checker_array << checkboard
else
checkboard += "\n"
checker_array << checkboard
end
count -= 1
else
checkboard = ("\u25A1 \u25A0 ") * (dimension / 2)
checkboard += "\u25A1"
checkboard += "\n"
checker_array << checkboard
count -= 1
end
end
checkboard = checker_array.join("")
checkboard
end
我应该添加/做什么来传递\n
在所需传递规范中的方式?
由于
答案 0 :(得分:0)
找出我自己的问题,解决方案在下面的代码中发表了评论
def checkered_board(dimension)
return false unless dimension.is_a?(Integer) && dimension >= 2
checkboard = nil
checker_array = []
spacer = " "
count = dimension
while dimension % 2 == 0 && count > 0 # set-up for even number passed in
if count % 2 == 0
checkboard = ("\u25A1#{spacer}\u25A0#{spacer}") * (dimension / 2)
checkboard = checkboard[0..-2] + "\n" #solution was here
checker_array << checkboard
count -= 1
else
checkboard = ("\u25A0#{spacer}\u25A1#{spacer}") * (dimension / 2)
if count == 1 #if count is the last number before 0, do not add \n to pass spec
checker_array << checkboard[0..-2] #solution was here
else
checkboard = checkboard[0..-2] + "\n" #solution was here
checker_array << checkboard
end
count -= 1
end
end
while dimension % 2 == 1 && count > 0 # set-up for odd number passed in
if count % 2 == 1
checkboard = ("\u25A0#{spacer}\u25A1#{spacer}") * (dimension / 2)
checkboard += "\u25A0"
if count == 1 #if count is the last number before 0, do not add \n to pass spec
checker_array << checkboard[0..-1] #solution was here
else
checkboard += "\n"
checker_array << checkboard
end
count -= 1
else
checkboard = ("\u25A1#{spacer}\u25A0#{spacer}") * (dimension / 2)
checkboard += "\u25A1"
checkboard = checkboard[0..-1] + "\n" #solution was here
checker_array << checkboard
count -= 1
end
end
checkboard = checker_array.join("")
checkboard
end