Control-D Issues in Ruby HW Problem - Observation by Patrick Finnigan ...

Patrick sends the following observation:

I think that I understand the issue brought up in class that CONTROL+D does not quit out of a while loop to get lines of text of input.

This code CAUSES THE PROBLEM where CONTROL+D will not exit:
-------------------
while (num = gets.to_i)
inputs.push(num)
end
-------------------


This code works and is problem free:
-------------------
while (num = gets)
inputs.push(num.to_i)
end
-------------------


What's the difference? The difference is, the "to_i" method CANNOT BE CALLED on the return of gets in the evaluation of the while loop here.

1. When we press CONTROL+D on Windows to insert an end of file character, gets returns nil
2. nil.to_i returns 0
3. Ruby evaluates 0 as "true" in the context of boolean expressions

Thus, any loop "while (x = gets.to_i)" will continue to loop forever. The to_i function must be called somewhere else within the while loop to convert the string returned by gets to an integer.

I tested and verified all of this in the IRB shell.
(screenshot below)

irb1