I have a file called "file1.txt":
Ruby
programming
is fun
In files.rb, which I'm calling from IRB, I have:
File.open('file1.txt', 'r') do |file|
while line = file.gets
puts "** " + line.chomp + " **" #--> why can't I use file.gets.chomp?
end
end
Why isn't line
and file.gets
interchangeable on line 3? If I switch line
with file.gets
, the function does not work, and I am a little bit perplexed considering that
line = file.gets
and
file.gets = line
should be interchangeable, but in this case, it is not as it gives me an error. The function works with line.chomp
.
I tried getting rid of the while
code block, and simply writing
puts file.gets
and it seems to output a line of code from file1.txt, but does not work inside the while
statement on line 3.
I'm not really into Ruby, but I think that is because if you use while line = file.gets
, the file.gets
return a line and read (and copy to buffer) the next one. In the final iteration, where the while is in the last line, the while line = file.gets
will return the last line. But in the while, you call again file.gets
, so as there are no more lines in file, it returns an error.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments