the12 the12 - 3 months ago 28
Ruby Question

Ruby Boolean assignment operator in a loop

Given the following code:'file1.txt', 'r') do |file|
while line = file.gets
puts "** " + line.chomp.reverse + " **"

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
to the return value of
, 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?

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

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


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.