2016-04-24 101 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」中的內容。