the12 the12 - 1 month ago 6
Ruby Question

Ruby Boolean assignment operator in a loop

Given the following code:

File.open('file1.txt', 'r') do |file|
while line = file.gets
puts "** " + line.chomp.reverse + " **"
end
end


I am confused to what is the question being asked? This is a simple piece of code I got off my tutorial, that reads a file's lines and puts it out. I do understand most of it, I believe you are assigning a variable
line
to the return value of
file.gets
, and it retrieves the value of those lines, and puts it out.

Where I am having trouble is the initial loop statement:
while line = file gets


My question is that what kind of question are you asking and how does it break out of the loop?

i.e.:
x=3 x ==3
--> You are asking is X equal to 3, if true will return
true
, if false will return
false
.

Also, are you simultaneously assigning the return value of
file.gets
to the variable
line
, in addition to putting it in the while statement?

Answer

In Ruby everything evaluates to truthy or falsey.

There are two falsey things:

  • nil
  • false

Everything else is truthy.

The while loop checks for truthiness of line variable.

Until it is anything but either nil or false it loops.

In your example the loop will stop when file.gets returns nil, meaning, there's no next line.