ruby koan三明治线计数
我正在处理Ruby Koans示例中的about_sandwich_代码示例,这里有完整的代码链接供参考。以下是相关参考代码,以便于参考ruby koan三明治线计数,ruby,block,Ruby,Block,我正在处理Ruby Koans示例中的about_sandwich_代码示例,这里有完整的代码链接供参考。以下是相关参考代码,以便于参考 def count_lines(file_name) file = open(file_name) count = 0 while file.gets count += 1 end count ensure file.close if file end def test_counti
def count_lines(file_name)
file = open(file_name)
count = 0
while file.gets
count += 1
end
count
ensure
file.close if file
end
def test_counting_lines
assert_equal 4, count_lines("example_file.txt")
end
# ------------------------------------------------------------------
def find_line(file_name)
file = open(file_name)
while line = file.gets
return line if line.match(/e/)
end
ensure
file.close if file
end
def test_finding_lines
assert_equal "test\n", find_line("example_file.txt")
end
def file_sandwich(file_name)
file = open(file_name)
yield(file)
ensure
file.close if file
end
在我尝试编写find_line2
方法时,我尝试了以下编译的代码
def find_line2(file_name)
file_sandwich(file_name) do |file|
while file.gets
return file.gets if file.gets.match(/e/)
end
end
end
def test_finding_lines2
assert_equal "test\n", find_line2("example_file.txt")
end
供参考
但是,KOAN在终端窗口中返回以下内容:预期“test\n”等于nil
这提高了我的意识,因为倒数第二个koan代码/模拟查找线函数的测试pre-sandwich代码解决了这个koan问题
def test_finding_lines
assert_equal "test\n", find_line("example_file.txt")
end
当我尝试不同的选项时,我意识到下面的find\u line2
实现
def find_line2(file_name)
file_sandwich(file_name) do |file|
while line = file.gets
return line if line.match(/e/)
end
end
当与
def test_finding_lines2
assert_equal "test\n", find_line2("example_file.txt")
end
解决了koan问题,而不是像前面的截图所示告诉我测试应该等于零。因此,正如我现在所理解的,这意味着我的第一个实现以某种方式改变了koan程序所期望的检查,这让我感到困惑。我想这意味着我的尝试以某种方式打破了koan,但我不知道为什么。实际上,在运行file\u sandwich
和我第一次实现find\u line2
之后,我看到调用find\u line2(“example\u file.txt”)
返回nil
,因此,出于某种原因,file.gets的作用不同于在while
语句中的line=file.gets之后使用line
有人能解释为什么我的第一个实现和答案不相等吗?我相信答案在于对积木有更清晰的理解
def find_line2(file_name)
file_sandwich(file_name) do |file|
while file.gets #gets the next line in the file
if file.gets.match(/e/) #gets the next line and checks for a match
return file.gets #gets the next line and returns it.
end #restructured for clarity
end
end
end
因此,对于示例文件:This\nis\na\ntest
您的代码获取This\n
,获取is\n
并检查它(失败)
。在下一次迭代中,代码获取a\n
,获取test\n
并检查它(true)
,然后获取下一行(nil)
,并返回它 在find_line2
中,while file.get;返回file.get;如果file.get.match(/e/);end
读取三个连续的行,前提是文件中还有三行。如果还有一两行,您将尝试读取文件末尾以外的内容,因此将引发异常。在任何情况下,如果line=file.get…
你想然后只参考line
。也许试着用更多的单词和更少的代码来表达你的问题?我不确定我是否理解你所说的“读取三行连续的数据,…因此会引发异常”—Cary Swoveland,也许你可以解释更多。我想最后,我只是不确定在while条件语句中使用line=file.get
与只使用file.get