【发布时间】:2014-05-01 03:01:30
【问题描述】:
我正在参与以下 Ruby Challenge GIST LINK
我的问题是,如何在“got:”之后阅读我的错误消息(如下)部分,以便更改我的正则表达式或#GSUB 表达式?
练习:打印一张时间表
实现一个名为 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)
但是,一旦我提交了挑战,我就会收到以下错误消息。
我的问题是,如何在“got:”之后阅读部分错误消息,以便更改我的正则表达式或#GSUB 表达式?
我无法找到“@@ -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 问题,所以如果我可以提供更多信息或更好的格式,请告诉我。 :)
提前致谢。
【问题讨论】:
-
请避免像这样使用所有大写字母,因为这会使您的问题难以阅读,而且看起来像是在大喊大叫!你为什么对我们大喊大叫?!?!?!
-
不要重复同样的问题。
-
更好的策略是简单的调试技术。我建议在每个正则表达式对其进行操作之前和之后打印出
nested_array_string。 -
您打印表格的方式过于复杂。
-
@Cupcake 我的错。只是想通过传递这么多数据来强调我的要求。