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

这样一段代码:
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:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值