Having trouble running a script from Learn Ruby the Hard Way

I am working out of “learn ruby the hard way” exercise 17. When I attempt to run the script this is the error message I get.

ex17.rb:11:in exist?': no implicit conversion of nil into String (TypeError) from ex17.rb:11:in

It’s tough to help without seeing the script. Maybe you have a typo. Or, based on the error, maybe you forgot to put quotes around a string. ¯\(ツ)

Agree with @kofo, we’d need to see the code really, but looks like something is (or has been made) nil when Ruby is expecting it to be a string.

My apologies, here it is…

from_file, to_file = ARGV

puts “Copying from #{from_file} to #{to_file}”

we could do these two on one line, how?

in_file = open(from_file)
indata = in_file.read

puts “the input file is #{indata.length} bytes long”

puts “Does the output file exist? #{File.exist?(to_file)}”
puts “Ready, hit RETURN to continue, CTRL-C to abort.”
$stdin.gets

out_file = open(to_file, ‘w’)
out_file.write(indata)

puts “Alright, all done”

out_file.close
in_file.close

That script takes two file names as command line arguments. Did you pass two file names in when you ran the script?

Also, your code will be easier to read if you use the code formatting option when posting it.

After you paste in your code, select it and then press the </> button on the toolbar. That will produce a nice code block like this:

from_file, to_file = ARGV  # <-- This is expecting two arguments passed into the script

puts "Copying from #{from_file} to #{to_file}"

# we could do these two on one line, how?
in_file = open(from_file)
indata = in_file.read

puts "the input file is #{indata.length} bytes long"

puts "Does the output file exist? #{File.exist?(to_file)}" #<-- This fails because to_file is never set to a value
puts "Ready, hit RETURN to continue, CTRL-C to abort."
$stdin.gets

out_file = open(to_file, 'w')
out_file.write(indata)

puts "Alright, all done"

out_file.close
in_file.close
1 Like

Thank you for your response. No I didn’t pass (2) arguments in the command line. I’ll try that. And I’ll remember to use the appropriate formatting next time.

Thanks again

1 Like