我正在开展以下Ruby挑战GIST LINK
实现一个名为times_table的方法,该方法将整数作为输入,并打印出一个包含该行数的时间表。
数字可以用任何空格或制表符分隔,但每行必须在新行上。这意味着如果列不排列就可以了。
例如,times_table(5)应将以下内容打印到屏幕上:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
同样,您无需担心列之间的间距。练习的目的是理解逻辑,而不是掌握格式。不过,你应该在数字之间至少有一个空格/制表符,否则它看起来不像时间表!
我写了下面的代码,它足以打印出一张时间表,虽然不是很漂亮。我认为这将满足练习的条件。
def times_table(rows)
return "Argument must be a positive integer" unless rows.is_a?(Integer) && rows > 0
array_of_arrays = []
base_array = (1..rows).to_a
counter = 1
1.upto(rows){
temp_array = base_array.map.with_index { |x,i| x *= counter}
array_of_arrays << temp_array
counter +=1
}
nested_array_string = array_of_arrays.to_s
nested_array_string.gsub!(/(\])/, "\n")
nested_array_string.gsub!(/(\[\[)|(, )/, " ")
nested_array_string.gsub!(/(\[)/, "")
nested_array_string.gsub!(/(^ )|(\n\z)/, "")
# nested_array_string.gsub!(/(\n\z)/, "")
end
puts times_table(1)
但是,一旦我提交了质询,我收到以下错误消息。
我无法找到代表“@@ -1,2 +1,2 @@”的答案。我假设(危险)最后的“/ +”表示匹配我的字符串值中的一个或多个空格的正则表达式。
Error!
times_table correctly prints a 1x1 times table
expected: /1\s*$/ got: "" (using =~) Diff: @@ -1,2 +1,2 @@ -/1\s*$/ +""
Error!
times_table correctly prints a 5x5 times table
expected: /1[ \t]+2[ \t]+3[ \t]+4[ \t]+5\s*\n2[ \t]+4[ \t]+6[ \t]+8[ \t]+10\s*\n3[ \t]+6[ \t]+9[ \t]+12[ \t]+15\s*\n4[ \t]+8[ \t]+12[ \t]+16[ \t]+20\s*\n5[ \t]+10[ \t]+15[ \t]+20[ \t]+25\s*$/m got: "" (using =~) Diff: @@ -1,2 +1,2 @@ -/1[ \t]+2[ \t]+3[ \t]+4[ \t]+5\s*\n2[ \t]+4[ \t]+6[ \t]+8[ \t]+10\s*\n3[ \t]+6[ \t]+9[ \t]+12[ \t]+15\s*\n4[ \t]+8[ \t]+12[ \t]+16[ \t]+20\s*\n5[ \t]+10[ \t]+15[ \t]+20[ \t]+25\s*$/m +""
注意:这是我的第二个StackOverflow问题,所以如果有更多信息或更好的格式,我可以告诉我。 :)
提前致谢。
答案 0 :(得分:0)
有些技术人员在正则表达式中谈论。一些规范也是如此,例如w3c XML规范 它是一种告诉你什么是他们期望的数据的可接受格式的方式 用正则表达式解析。
在这种情况下,看起来他们正在告诉你字符串的形式是什么 他们的验证器与正则表达式不匹配 - 预期 之后的事情。
他们 得到了什么 我猜,这是比赛的结果,即""
??
不知道,但那就是我的样子。
所以,猜测提交的字符串不匹配
你有没有在数字和换行符之间添加空格?
expected: /1[ \t]+2[ \t]+3[ \t]+4[ \t]+5\s*\n2[ \t]+4[ \t]+6[ \t]+8[ \t]+10\s*\n3[ \t]+6[ \t]+9[ \t]+12[ \t]+15\s*\n4[ \t]+8[ \t]+12[ \t]+16[ \t]+20\s*\n5[ \t]+10[ \t]+15[ \t]+20[ \t]+25\s*$/m
got: ""