Ruby 中的 STDIN 和 $stdin 有什么区别? [英] What is the difference between STDIN and $stdin in Ruby?

查看:42
本文介绍了Ruby 中的 STDIN 和 $stdin 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 有两种引用标准输入的方式:STDIN 常量和 $stdin 全局变量.

Ruby has two ways of referring to the standard input: The STDIN constant , and the $stdin global variable.

除了我可以将不同的 IO 对象分配给 $stdin 的事实之外,因为它不是一个常量(例如在我的孩子中分叉重定向 IO 之前),还有什么STDIN$stdin 的区别?我什么时候应该在我的代码中使用每一个?

Aside from the fact that I can assign a different IO object to $stdin because it's not a constant (e.g. before forking to redirect IO in my children), what's the difference between STDIN and $stdin? When should I use each in my code?

如果我重新分配$stdin,会影响STDIN吗?

If I reassign $stdin, does it affect STDIN?

这是否也适用于 STDOUT/$stdoutSTDER/$stderr?

And does this also apply to STDOUT/$stdout and STDER/$stderr?

推荐答案

如果 $stdin 被重新分配,STDIN 不受影响.同样,当 STDIN 被重新分配时,$stdin 不受影响(这是完全可能的(虽然毫无意义),但会产生警告).然而,如果两个变量都没有被重新赋值,它们都指向同一个 IO 对象,所以对一个调用 reopen¹ 会影响另一个.

If $stdin is reassigned, STDIN is not affected. Likewise $stdin is not affected when STDIN is reassigned (which is perfectly possible (though pointless), but will produce a warning). However if neither variable has been reassigned, they both point to the same IO object, so calling reopen¹ on one will affect the other.

所有内置的 ruby​​ 方法都使用 $<(又名 ARGF)来读取输入.如果ARGV为空,ARGF$stdin读取,所以如果你重新赋值$stdin,会影响所有内置方法.如果您重新分配 STDIN,它将无效,除非某些 3rd 方方法使用 STDIN.

All the built-in ruby methods use $< (a.k.a. ARGF) to read input. If ARGV is empty, ARGF reads from $stdin, so if you reassign $stdin, that will affect all built-in methods. If you reassign STDIN it will have no effect unless some 3rd party method uses STDIN.

在您自己的代码中,您应该使用 $stdin 以与内置方法保持一致².

In your own code you should use $stdin to be consistent with the built-in methods².

¹ reopen 是一种可以将 IO 对象重定向到另一个流或文件的方法.但是,您不能使用它来将 IO 重定向到 StringIO,因此它不会消除重新分配 $stdin 的所有用例.

¹ reopen is a method which can redirect an IO object to another stream or file. However you can't use it to redirect an IO to a StringIO, so it does not eliminate all uses cases of reassigning $stdin.

² 你当然也可以使用 $</ARGF 来与内置方法更加一致,但大多数时候你如果您明确使用标准输入流,则不需要 ARGF 行为.

² You may of course also use $</ARGF to be even more consistent with the built-in methods, but most of the time you don't want the ARGF behavior if you're explicitly using the stdin stream.

这篇关于Ruby 中的 STDIN 和 $stdin 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆