简体   繁体   中英

undefined method `chomp' for nil:NilClass (NoMethodError)

I have entered the following code from Zed Shaw's book on "Learning Ruby the Hard Way

input_file = ARGV.first #this takes the file test.txt

def print_all(f) #reading a line
puts f.read
end

 def rewind(f)
 f.seek(0)
 end

   def print_a_line(line_count, f)                
   current_line
   puts "#{line_count}, #{f.gets.chomp}"
   end

  current_file = open(input_file)

 puts "First let's print the whole file:\n"

 print_all(current_file)

 puts "Now let's rewind, kind of like a tape"

rewind(current_file)

puts "Let's print three line:"

current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

The error I am getting is 'ex20.rb:12:in print_a_line': undefined method chomp' for nil:NilClass (NoMethodError) from ex20.rb:31:in `'

Any help would be greatly appreciated. I have followed his example word by word.

You have to add a few more lines to the test.txt file (at least three lines of text for each of the method calls you do at the end).

I ran across the same issue because the lesson isn't exactly clear about it, but since the script prints out three lines in a row, you need 3 lines of text in the file for the script to work.

在您的test.txt文件中添加更多行

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM