您的位置:首页 > 编程语言 > Ruby

关于Ruby的ARGV与gets语句同时使用的问题

2016-06-28 14:54 513 查看
这样一段代码:

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?qwer
This is from your .gets:qwer
This is from ARGV a:
This is from ARGV b:

以上输出没有任何报错。

但是如果命令中带有参数(ARGV),即如下命令:

D:\rubylearn> ruby ex7.rb 1 2

则会出现如下的报错:

the script is called:ex7.rb
adsfa?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 = ARGV
puts "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?qwer
This is from your .gets:qwer
This is from ARGV a:
This is from ARGV b:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: