问题描述
我的 ruby 脚本从命令行参数获取某些输入.它检查是否缺少任何命令行参数,然后提示用户输入.但是我无法使用gets从用户那里获得输入.
My ruby script gets certain inputs from command line arguments. It check if any of the command line argument is missing, then it prompts for an input from user. But i am not able to get input from user using gets.
示例代码:test.rb
Sample code: test.rb
name=""
ARGV.each do|a|
if a.include?('-n')
name=a
puts "Argument: #{a}"
end
end
if name==""
puts "enter name:"
name=gets
puts name
end
运行脚本:ruby test.rb raghav-k
导致错误:
test.rb:6:in `gets': No such file or directory - raghav-k (Errno::ENOENT)
from test.rb:6:in `gets'
from test.rb:6:in `<main>'
任何在这个方向上的指点将不胜感激谢谢桑迪
Any pointers in this direction will be really gratefulThanksSandy
推荐答案
gets
如果没有命令,只会从真正的 $stdin
(即用户)读取行参数.否则,它会将这些参数作为文件连接为虚拟 $stdin
.
gets
will only read from the real $stdin
(ie the user) if there are no command line arguments. Otherwise it'll take those arguments as files to concatenate as a virtual $stdin
.
您可以使用 STDIN.gets
来确保您始终使用正确的函数.
You can use STDIN.gets
to make sure you're always using the right function.
您也可以随时从 ARGV
中删除参数(或一次性删除它们),您的 gets
应该可以正常工作.
You can also delete the arguments from ARGV
as you go (or remove them all in one go), your gets
should work correctly.
这篇关于ruby 中的相同程序如何接受来自用户的输入以及命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!