In `open': no implicit conversion of nil into String (TypeError) from ex30.rb:3:in `<main>'

From “Learn Ruby The Hard Way” exercise 15 — http://learnrubythehardway.org/book/ex15.html
filename = ARGV.first

This is the file I created which I saved as ex30.rb :

txt = open(filename)

puts “Here’s your file #{filename}:”
print txt.read

print "Type the filename again: "
file_again = $stdin.gets.chomp

txt_again = open(file_again)

print txt_again.read

This is the error I received :

CaiGengYangs-MacBook-Pro:GoatBoy CaiGengYang$ ruby ex30.rb
ex30.rb:3:in open': no implicit conversion of nil into String (TypeError) from ex30.rb:3:in

How to debug this ?

filename var is nil… that means it was expecting an argument that’s missing…

The correct way to run the script should be: ruby ex30.rb some_filename.txt

where some_filename.txt exists.

I still get an error message though —

CaiGengYangs-MacBook-Pro:GoatBoy CaiGengYang$ ruby ex30.rb some_filename.txt
ex30.rb:3:in initialize': No such file or directory - some_filename.txt (Errno::ENOENT) from ex30.rb:3:in open’
from ex30.rb:3:in `’

You probably missed a paragraph, while working on the exercise.

This exercise involves writing two files. One is the usual ex15.rb file that you will run, but the other is named ex15_sample.txt. This second file isn’t a script but a plain text file we’ll be reading in our script. Here are the contents of that file:

This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

You then run your script with

$ ruby ex15.rb ex15_sample.txt

as stated in the same exercise.

1 Like

i also specified…where some_filename.txt exists… i just tried to explain the origin of this error :slight_smile:

Ok, it works now. I created a file called ex30_sample.txt and ran the script and to works. Here’s my output.

CaiGengYangs-MacBook-Pro:GoatBoy CaiGengYang$ ruby ex30.rb ex30_sample.txt
Here’s your file ex30_sample.txt:
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.Type the filename again: ex30_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.