它们是相同的,还是两个命令之间有细微的差异?
发布于 2012-05-10 04:27:30
gets将使用Kernel#gets,它首先尝试读取通过ARGV传入的文件的内容。如果ARGV中没有文件,它将使用标准输入(在这一点上它与STDIN.gets相同。
注意:正如echristopherson指出的那样,Kernel#gets实际上将退回到$stdin,而不是STDIN。但是,除非您将$stdin分配给不同的输入流,否则默认情况下,它将与STDIN相同。
http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-gets
发布于 2013-11-06 05:21:16
gets.chomp() =首先读取ARGV
STDIN.gets.chomp() =读取用户输入
发布于 2017-02-19 09:49:20
如果您的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} ?"然后你在终端中运行
$ ruby color.rb blue yellow green它将抛出一个错误(没有这样的文件错误)
现在将下面这行中的'gets.chomp‘替换为'stdin.gets.chomp’
least_fav_color = $stdin.gets.chomp并在终端中运行以下命令
$ ruby color.rb blue yellow green然后你的程序就会运行!
基本上,一旦你从get go开始调用ARGV (正如ARGV设计的那样),gets.chomp就不能再正常工作了。是时候引进大炮了:$stdin.gets.chomp
https://stackoverflow.com/questions/10523536
复制相似问题