programmer321 programmer321 - 1 month ago 7
Ruby Question

In Ruby, why aren't variables not interchangeable within code blocks?

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 if I set

line = file.gets


then

file.gets = line


and 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 inside the
while
it does not work if written on line 3, only the variable line works.

Answer

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.