ruby get.chomp() 与 STDIN.gets.chomp() 之间有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10523536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:06:34  来源:igfitidea点击:

What's the difference between gets.chomp() vs. STDIN.gets.chomp()?

ruby

提问by stanigator

Are they the same, or are there subtle differences between the two commands?

它们是相同的,还是两个命令之间存在细微差别?

回答by Dylan Markow

getswill use Kernel#gets, which first tries to read the contents of files passed in through ARGV. If there are no files in ARGV, it will use standard input instead (at which point it's the same as STDIN.gets.

gets将使用Kernel#gets,它首先尝试读取通过ARGV. 如果 中没有文件ARGV,它将改用标准输入(此时它与STDIN.gets.

Note: As echristopherson pointed out, Kernel#getswill actually fall back to $stdin, not STDIN. However, unless you assign $stdinto a different input stream, it will be identical to STDINby default.

注意:正如 echristopherson 所指出的,Kernel#gets实际上会回退到$stdin,而不是STDIN。但是,除非您分配$stdin给不同的输入流,否则STDIN默认情况下它将相同。

http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-gets

http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-gets

回答by Rick Lien

gets.chomp()= read ARGVfirst

gets.chomp()=ARGV先读

STDIN.gets.chomp()= read user's input

STDIN.gets.chomp()= 读取用户的输入

回答by cjpillette

If your color.rb file is

如果您的 color.rb 文件是

first, second, third = ARGV

puts "Your first fav color is: #{first}"
puts "Your second fav color is: #{second}"
puts "Your third fav color is: #{third}"

puts "what is your least fav color?"
least_fav_color = gets.chomp

puts "ok, i get it, you don't like #{least_fav_color} ?"

and you run in the terminal

然后你在终端中运行

$ ruby color.rb blue yellow green

it will throw an error (no such file error)

它会抛出一个错误(没有这样的文件错误)

now replace 'gets.chomp' by 'stdin.gets.chomp' on the line below

现在在下面的行中将 'gets.chomp' 替换为 'stdin.gets.chomp'

least_fav_color = $stdin.gets.chomp

and run in the terminal the following command

并在终端中运行以下命令

$ ruby color.rb blue yellow green

then your program runs!!

然后你的程序运行!

Basically once you've started calling ARGV from the get go (as ARGV is designed to) gets.chomp can't do its job properly anymore. Time to bring in the big artillery: $stdin.gets.chomp

基本上,一旦您从一开始就开始调用 ARGV(正如 ARGV 设计的那样),gets.chomp 就不能再正常工作了。是时候引进大炮了:$stdin.gets.chomp

回答by Shoot Sahan

because if there is stuff in ARGV, the default gets method tries to treat the first one as a file and read from that. To read from the user's input (i.e., stdin) in such a situation, you have to use it STDIN.gets explicitly.

因为如果 ARGV 中有东西,默认的 gets 方法会尝试将第一个文件视为文件并从中读取。要在这种情况下读取用户的输入(即 stdin),您必须显式使用它 STDIN.gets。