Dan Zwell
8/17/2007 2:41:00 AM
Jonathan Carbon wrote:
> Hi Dan,
>
> thanks very much for the response. The program does not seem to get to
> end when just the enter is pressed...
> Im doing my best to understand...
>
> Sorry to be so thick!
Not at all, the thickness is mine...
>
> Thanks!
>
>
Giving advice without testing it is a bad habit of mine. I wasn't paying
attention to Ruby's precedence. Apparently,
while line = gets.chomp && line != ""
needs some parentheses:
while (line = gets.chomp) && line != ""
However, there's another small gotcha. When you write a loop
while line = gets.chomp; something; end
users will often end the loop by hitting control-d, which means "end of
file" (on unix/linux, at least). This causes gets() to return nil, and
in that case, line.chomp throws an error (nil lacks the method chomp()).
This does what you want and also handles the control-d case:
while line=gets and line.chomp != ""
Note that the chomp() is not cached in this case--in the body of the
loop, you need to call chomp() when you refer to the line, or just call
"line.chomp!". You could probably be more efficient, but often the Ruby
way is either the most easily readable thing, or the most elegant.
Dan