我有一个名为“ file1.txt”的文件:
Ruby
programming
is fun
在从IRB调用的files.rb中,我具有:
File.open('file1.txt', 'r') do |file|
while line = file.gets
puts "** " + line.chomp + " **" #--> why can't I use file.gets.chomp?
end
end
为什么不line
和file.gets
第3行互换?如果我转line
用file.gets
,该功能不工作,我感到有点困惑考虑
line = file.gets
和
file.gets = line
应该可以互换,但是在这种情况下,它不是,因为它给了我一个错误。该函数与配合使用line.chomp
。
我试图摆脱while
代码块,只是写
puts file.gets
并且似乎从file1.txt输出了一行代码,但是while
在第3行的语句中不起作用。
我不是很喜欢Ruby,但是我认为这是因为,如果您使用while line = file.gets
,则file.gets
返回一行并读取(并将其复制到缓冲区中)下一行。在最后一次迭代中,while在最后一行,而while line = file.gets
将会返回最后一行。但是在此期间,您再次调用file.gets
,因此文件中没有更多行,它将返回错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句