簡體   English   中英

命令行參數和`gets`

[英]Command line arguments and `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}"

如果沒有$stdin我無法接受使用gets命令的用戶輸入。 我必須使用$stdin.gets才能使其正常工作。

這是為什么? ARGV做了什么來禁用它? 默認情況下, gets命令中不包含$stdin嗎?

gets函數文檔:

從 ARGV(或 $*)中的文件列表中返回(並分配給 $_)下一行,如果命令行上沒有文件,則從標准輸入中返回。

因此,如果您將命令行參數傳遞給您的 ruby​​ 程序, gets將不再從$stdin讀取,而是從您傳遞的那些文件中讀取。

想象一下,我們在名為argv.rb的文件中有一個較短的代碼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”中的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM