Ruby 中 $stdout 和 STDOUT 之间的区别
在 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
.
Edit: Just found a related question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
$stdout
是一个全局变量,表示当前的标准输出。STDOUT
是表示标准输出的常量,通常是$stdout
的默认值。由于
STDOUT
是常量,您不应该重新定义它,但是,您可以重新定义$stdout
而不会出现错误/警告(重新定义STDOUT
将发出警告)。例如,您可以这样做:$stderr
和STDERR
也是如此因此,要回答问题的其他部分,请使用全局变量来重定向输出,而不是常量。只是要小心在代码中进一步更改它,重新定义全局变量可能会影响应用程序的其他部分。
$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
.With
STDOUT
being a constant, you shouldn't re-define it, however, you can re-define$stdout
without errors/warnings (re-definingSTDOUT
will raise a warning). for example, you can do:Same goes for
$stderr
andSTDERR
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.
$stdout
和STDOUT
都有不同的含义。 Ruby 文档 关于这个主题非常清楚:当您想要写入标准输出时,您实际上指的是当前标准输出,因此您应该写入
$stdout
。STDOUT
也不是没用。它存储$stdout
的默认值。如果您重新分配了$stdout
,则可以使用$stdout = STDOUT
将其恢复为之前的值。此外,还有一个预定义变量:
然而,在 Ruby 2.3 中,它看起来只是充当
$stdout
的别名。重新分配$stdout
会更改$>
的值,反之亦然。Both
$stdout
andSTDOUT
have different meanings. Ruby's documentation is pretty clear on this topic:When you want to write to the standard output, then you actually mean the current standard output, thus you should write to
$stdout
.STDOUT
isn't useless too. It stores the default value for$stdout
. If you ever reassign$stdout
, then you can restore it to the previous value with$stdout = STDOUT
.Furthermore, there's one more predefined variable:
However it looks like in Ruby 2.3 it simply behaves as an alias for
$stdout
. Reassigning$stdout
changes the value of$>
and vice versa.STDOUT
是一个全局常量,因此不应更改。$stdout
是一个预定义变量,因此可以更改。如果您使用 shell 进行重定向:
那么在执行脚本之前确定使用哪一个作为脚本的文件描述符并不重要。
但是,如果您尝试在 Ruby 脚本中更改操作系统 STDOUT 的文件描述符,例如根据当前星期几将输出发送到一组轮换的日志文件,那么您需要确保您使用
$stdout
。STDOUT
is a global constant, so it should not be changed.$stdout
is a predefined variable, so it can be changed.If you are using the shell to do redirection:
then it doesn't matter which one you use as the file descriptor for your script is being determined before your script is executed.
However, if you are trying to change the file descriptor for the OS's STDOUT from within your Ruby script, for example to send output to a rotating set of log files based on the current day of the week, then you'll want to make sure you use
$stdout
.