打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
关于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:
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
ruby笔记
ruby 文件操作
Ruby
ruby系列教材(4):Control Structures
Perl语言入门_中文版_第六版程序
http://developer.51cto.com/art/201007/211543....
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服