fvertk
fvertk

Reputation: 169

Running a ruby script from another, weird error using "gets"

I have written a ruby script that then calls another ruby script. The callee script is very long and has a lot of "gets" for input.

So what I do is open my unix terminal, call the caller script, which then does this simple line:

load "calleeScript.rb"

The calleeScript.rb has been simplified to just do this:

input = gets.chomp

print input

But it just gives me an error, like it can't handle gets. The error says:

./getsTest.rb:3:in `gets': No such file or directory - 5 (Errno::ENOENT) from ./getsTest.rb:3

Even if I take out that gets it won't print/puts to the terminal. So any idea how I call one script that then calls another script (either relinquishing total control or forking), do some inputs/outputs, and still return to the previous script?

Upvotes: 1

Views: 290

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369438

Kernel#gets is a convenience method that allows you to handle input both via standard input and via files.

If you call your script without any arguments, i.e. like this:

getsTest.rb

Then Kernel#gets reads its input from standard input. If, however, you call your script like this:

getsTest.rb foo.txt

Then Kernel#gets reads its input from a file named foo.txt.

In your case, Kernel#gets is complaining that it can't find a file named 5, so presumably you called your script something like this:

getsTest.rb 5

If you want to read from some specific source, you should call IO#gets on that specific source. I suggest calling

$stdin.gets

Note: technically speaking, this is not a feature of Kernel#gets but rather of the ARGF magic constant. Basically, Kernel#gets just calls ARGF.gets.

Upvotes: 4

Related Questions