这样一段代码:
a , b = ARGV
puts "the script is called:#{$0}"
print "adsfa?"
d = gets.chomp()
# d = $stdin.gets.chomp()
puts "This is from your .gets:#{d}"
puts "This is from ARGV a:#{a}"
puts "This is from ARGV b:#{b}"
执行如下命令时:
D:\rubylearn> ruby ex7.rb
产生这样的输出:
the script is called:ex7.rb
adsfa?qwerThis is from your .gets:qwerThis is from ARGV a:This is from ARGV b:
以上输出没有任何报错。
但是如果命令中带有参数(ARGV),即如下命令:
D:\rubylearn> ruby ex7.rb 1 2
则会出现如下的报错:
the script is called:ex7.rbadsfa?ex7.rb:6:in `gets': No such file or directory - 1 (Errno::ENOENT)from ex7.rb:6:in `gets' from ex7.rb:6:in `'
接下来是干货:
原因分析:当ruby代码执行后面带有参数(ARGV)时,其程序体中的gets命令会降低一个参数认为是文件名,并尝试从其中读取输入字符(行),相当于重定向了input接口。因此,如果需要在程序中从标准输入源(键盘)读取输入,则需要在程序体重制定gets的执行方式:
input = $stdin.gets
因此,以上程序应该改为:
a , b = ARGVputs "the script is called:#{$0}"print "adsfa?"d = $stdin.gets.chomp()puts "This is from your .gets:#{d}"puts "This is from ARGV a:#{a}"puts "This is from ARGV b:#{b}"
这次运行正常了:
D:\rubylearn> ruby ex7.rb
输出:
the script is called:ex7.rb
adsfa?qwerThis is from your .gets:qwerThis is from ARGV a:This is from ARGV b: