Ruby 中 $stdout 和 STDOUT 的区别 [英] Difference between $stdout and STDOUT in Ruby
问题描述
在 Ruby 中,$stdout
(以美元符号开头)和 STDOUT
(全部大写)之间有什么区别?做输出重定向时,应该使用哪个,为什么?$stderr
和 STDERR
也是如此.
In Ruby, what is the difference between $stdout
(preceded by a dollar sign) and STDOUT
(in all caps)? When doing output redirection, which should be used and why? The same goes for $stderr
and STDERR
.
刚刚发现了一个 相关问题.
推荐答案
$stdout
是一个全局变量,表示当前的标准输出.STDOUT
是表示标准输出的常量,通常是 $stdout
的默认值.
$stdout
is a global variable that represents the current standard output. STDOUT
is a constant representing standard output and is typically the default value of $stdout
.
由于 STDOUT
是一个常量,您不应该重新定义它,但是,您可以重新定义 $stdout
而不会出现错误/警告(重新定义 STDOUT
将引发警告).例如,你可以这样做:
With STDOUT
being a constant, you shouldn't re-define it, however, you can re-define $stdout
without errors/warnings (re-defining STDOUT
will raise a warning). for example, you can do:
$stdout = STDERR
同样适用于 $stderr
和 STDERR
因此,要回答问题的另一部分,请使用全局变量来重定向输出,而不是常量.请小心在代码中进一步更改它,重新定义全局变量可能会影响应用程序的其他部分.
So, to answer the other part of your question, use the global variables to redirect output, not the constants. Just be careful to change it back further on in your code, re-defining global variables can impact other parts of your application.
这篇关于Ruby 中 $stdout 和 STDOUT 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!