When calling a second program via load, gets reads from ARGV[0] of original program

StackOverflow https://stackoverflow.com/questions/19531415

  •  01-07-2022
  •  | 
  •  

Question

Consider a file named weird1.rb:

load 'weird2.rb'

and weird2.rb:

p = gets.chomp
puts "Got input: #{p}"

When I run weird1.rb without any argument, gets reads the user's input from the console:

c:\a\ruby>weird1.rb
test
Got input: test

When I run it with an argument, gets reads from the argument given (someRandomArg and weird2.rb, respectively in the cases below):

c:\a\ruby>weird1.rb someRandomArg
weird2.rb:1:in `gets': No such file or directory - someRandomArg (Errno::ENOENT)

c:\a\ruby>weird1.rb weird2.rb
Got input: p = gets.chomp

Why is weird2 reading from weird1's argument? This seems unexpected; gets is supposed to read from stdin, not a file. What is happening, and how do I fix this?

Was it helpful?

Solution

The load part has nothing to do with it. The same thing should happen if you directly call weird2.rb with and without an argument.

The effect you're seeing is that gets functions like a unix filter, which means it will read from STDIN if no file is specified, or else the file(s) provided via the command line.

If you're doing some preprocessing via weird.rb, then remove any args off of ARGV via shift before loading weird2.rb, like such:

my_arg = ARGV.shift
# do stuff with my_arg
load 'weird2.rb'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top