2016-04-24 102 views
1

在下面的脚本:命令行参数和`gets`

first, second, third = ARGV 

puts "The oldest brothers name is #{first}" 
puts "The middle brothers name is #{second}" 
puts "The youngest brothers name is #{third}" 

puts "What is your moms name?" 
mom = $stdin.gets.chomp 

puts "What is your dads name?" 
dad = $stdin.gets.chomp 

puts "In the my family there are three sons #{first}, #{second}, #{third}, and a mom named #{mom}, and a father named #{dad}" 

使用gets命令没有$stdin我不能接受用户输入。我必须使用$stdin.gets才能正常工作。

这是为什么? ARGV是做什么来禁用它的?默认情况下$stdingets命令不包含在内?

+0

无法复制。只要您在终端调用脚本时不传递任何参数,它就会在代码中引用'ARGV'并且不使用'$ stdin'。 – sawa

+0

它看起来好像是用3个参数调用脚本,列出3个兄弟的名字。如果这些名称恰好是文件,那么'gets'将会读取它们,否则不会。 – user12341234

回答

1

gets函数文档:

返回(并分配到$ _)argv中的下一行从文件列表(或$ *),或从标准输入,如果没有文件存在于命令行。

所以,如果你通过命令行参数的Ruby程序,gets将不再从$stdin读取,而是从那些文件你通过。

假设我们有一个文件中的代码调用argv.rb更短的例子:

first, second = ARGV 

input = gets.chomp 

puts "First: #{first}, Second: #{second}, Input #{input}" 

我们创建下列文件:

$ echo "Alex" > alex 
$ echo "Bob" > bob 

并且可以运行我们的程序一样ruby argv.rb alex bob,输出将是:

First: alex, Second: bob, Input Alex 

请注意,值input是“Alex”,因为那是第一个文件'alex'的内容。如果我们第二次拨打gets,返回的值将是“Bob”,因为这就是下一个文件“bob”中的内容。