Ex 20 Error with gets.chomp in print_a_line

This is not the first time I’ve gotten a .chomp error that I could not resolve. Even after copy/paste of @zedshaw code.

Here is the error:

ex20.rb:12:in `print_a_line': undefined method `chomp' for nil:NilClass (NoMethodError)
	from ex20.rb:31:in `<main>'

Here is my code:

input_file = ARGV.first

def print_all(f)
	puts f.read
end

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

def print_a_line(line_count, f)
	puts "#{line_count}, #{f.pos}"
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 lines:"

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)

That is an odd error because you are not calling .chomp on anything. First up, make sure you’re running it with the correct command line:

ruby ex20.rb test.txt

Then make sure that you’re actually posting the code you think you are. In this code there’s no .chomp anywhere, but your error mentions it.

Posting Code

Remember that when you post code you can do this:

[code]
# your ruby here
[/code]

I did this for you in your post so you can see what I did. You can hit the … and that opens the bigger menu then click the pencil.

Thank you for taking the time to look into this. I had my files all mixed up. I never thought to check that, so thank you!

Classic mistake. A quick way to make sure you’re running the right code is put a really weird bad code line in it. I do something like a syntax error:

BUG

That should blow up if you’re running the right code. If it doesn’t, you have the wrong one.

That’s fantastic. What a simple way to make things better! Thank you!