Ruby stdio 常量和全局变量有什么用?
Ruby 有 stdio 的常量和全局变量。
即,常量 STDIN
、STDOUT
、STDERR
及其对应变量 $stdin
、$标准输出,
$stderr
。
我理解常量和变量之间的区别。我知道在执行脚本时,常量被不变地设置为文件描述符。
我还了解您可以在运行时更改(某些)变量。
我对此类功能的实际用途很好奇。你为什么要这么做?你能取得什么成就?
看到一些从现实世界项目中提取的示例代码,甚至只是用例,那就太棒了。
更新:从我到目前为止收集到的信息来看,似乎在编写自己的库/程序时,您应该更喜欢使用变量而不是常量,以便用户可以进一步使用它。正确的?
Ruby has constants and global variables for stdio.
Namely, the consts STDIN
, STDOUT
, STDERR
, and their variable counterparts, $stdin
, $stdout
, $stderr
.
I understand the difference between a constant and a variable. I know the constants are immutably set to the file descriptors at the moment the script was exec'd.
I also understand that you can change (some of) the variables at runtime.
I'm curious regarding practical uses of such feature. Why would you want to do it? What can you achieve?
Seeing some sample code, or even just use cases, extracted from real world projects would be awesome.
Update: From what I gather so far, it seems that when writing your own libraries/programs, you should prefer to use the variables over the constants, so that its users can further muck with it. Right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
该函数的一个更复杂的版本正在生产代码中使用:
它用于想要了解使用
print
或puts
写入控制台的内容的单元测试。$
变量让您可以为 Ruby 提供不同的 IO 对象(stdout、stdin、stderr):这些常量可以轻松地将
$
变量恢复到其原始状态(当您的程序启动时) ) 价值:A more elaborate version of this function is in use in production code:
It is used in unit tests that want to know what was written to the console using
print
orputs
.The
$
variables let you give Ruby different IO objects for stdout, stdin, stderr:the constants make it easy to get the
$
variables back to their original (when your program started) value:松本的书似乎给出了答案。引自 9.7.1.4 预定义流:“默认情况下,诸如
print
和puts
之类的全局函数会写入 $stdout。如果脚本更改了这个全局变量,它将改变这些方法的行为。”在我看来,这个想法似乎只是为一个可能实施不善的程序提供一个简单的解决方案。
Matsumoto's book on it seems to give the answer. Quote from 9.7.1.4 Predefined streams: "Global functions like
print
andputs
write to $stdout by default. If a script alters the value of this global variable, it will change the behavior of those methods."It sounds to me as if the idea is to simply allow an easy solution to a possibly poorly implemented program.
所有错误都会写入error.log
All errors will be written to error.log
您可以将部分输出发送到文件,然后在完成后将其转储回控制台。
You can send part of your output to a file and then dump it back to the console when you're done.