1

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?

1
  • 1
    I would prefer IO.foreach("file1.txt") { |line| puts "** " + line.chomp.reverse + " **" }. See IO::foreach. (This is often written File.foreach(..., which works because File is a subclass of IO). Commented Nov 1, 2016 at 21:39

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Ok and truthy and falsy refers to is the data type set by Ruby to true or false?
@the12 Predicates typically return one of the Boolean values true or false, but this is not required, as any value other than false or nil works like true when a Boolean value is required. Meaning while 2 would work, as well as while true or while 'hello world'
Ok and just to double check, you are assigning the value of file.gets to the variable line AND putting it in the while statement?
@the12 yes, assigning operator here takes precedence, so while foo = 2 actually evaluates to while 2 which basically means while true.
@the12: assignment operator returns value that was assigned. That's why it is possible to simultaneously assign some variable and test it in a conditional.
|
1

What happens is that while is using the variable line as its condition. line = file.gets is assigned before while checks the condition. Additionally, while knows how to break out of the loop because at EOF file.gets returns nil which is false-y.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.