Stefano Crocco
11/5/2008 12:59:00 PM
Alle Wednesday 05 November 2008, Zhenning Guan ha scritto:
> when I was running this code
> ------------
> File.open("1c.txt") do |f|
> while line= f.gets.chomp;
> p line ;
> end
> end
> -------------
>
> why they warning with the message below?
>
> =========
> private method 'chomp' called for nil:NilClass <nomethoderror>
> from ok.rb:2:in 'open'
> from ok.rb:2
> ==========
Because chomp will be called on the value returned by f.gets, even when it's
nil. You need to move the call to chomp inside the while loop:
while line=f.gets
line = line.chomp #or simply line.chomp!
...
You can also add a rescue clause inside the condition of the while loop:
while (line = f.gets.chomp rescue nil)
...
This way, when f.gets returns nil and the NoMethodError exception is raised,
the exception is rescued and line is set to nil, which causes the loop to end.
I hope this helps
Stefano