AltBrian
AltBrian

Reputation: 2562

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.

Upvotes: 1

Views: 3036

Answers (2)

C.Chaney
C.Chaney

Reputation: 76

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.

Upvotes: 3

fkdlsajlfk
fkdlsajlfk

Reputation: 11

add more lines to your test.txt file

Upvotes: 1

Related Questions