关于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:
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:
相关文章推荐
- ruby学习笔记
- ruby 安装gem报错:`SSL_set_tlsext_host_name' was not declared in this scope
- 记录一次logstash 死锁问题
- ruby 生成随机数 和 随机字符串
- CocoaPods安装以及相关问题解决
- ruby gem 记录
- ruby使用Net::SSH和Net::SCP,实现远程命令执行
- sass学习(入门篇)
- 使用chruby管理ruby版本
- Ruby+watir自动化测试中实现识别验证码图片
- Cocoa pods 的安装 以及使用介绍
- Ruby调用Hadoop集群实战(草稿)
- Ruby on Rails(二) - 初探Ruby on Rails, 搭建一个博客项目并发布(草稿)
- Ruby on Rails(一) - Ubuntu16.04 安装Ruby on Rails全过程, 亲测可用
- Ruby的DevKit名词解释
- 关于CocoaPod安装常见问题
- php不是世界上最好的语言, Ruby才是
- Vagrant和VirtualBox搭建基于windows的Ruby on Rails基本开发环境(共享文件夹配置)
- innodb结构解析工具---innodb_ruby
- Ruby on Rails实现最基本的用户注册和登录功能的教程