简体   繁体   English

Ruby全局变量,合法用途

[英]Ruby global variables, legitimate uses

I've never seen global variables used in any Ruby code. 我从来没有见过任何Ruby代码中使用的全局变量。 I understand that their use is frowned upon across languages but they seem actually useless in Ruby. 我知道他们的使用在各种语言中都是不受欢迎的,但它们在Ruby中似乎毫无用处 Can anyone point to properly designed code that uses them? 任何人都可以指出使用它们的设计合理的代码吗?

If I'm right and they're redundant/historical, why do they persist in 1.9? 如果我是对的,他们是多余的/历史的,为什么他们坚持1.9?

To be clear, I don't mean variables that Ruby sets up for you like $" and $stdin . I mean uses in one's own code. 要清楚,我并不是指Ruby为你设置的变量,如$"$stdin 。我的意思是在一个人自己的代码中使用。

The only time I see it in decent code is for a log. 我在体面的代码中看到它的唯一一次是日志。

$log = Logger.new('foo.log', 'daily')

A constant would probably do fine, but it somehow feels strange calling methods on a constant. 一个常量可能会很好,但它在某种程度上感觉很奇怪调用常量上的方法。

Environment variables are usually Global variables in Ruby. 环境变量通常是Ruby中的全局变量。 So are CLASSPATH in jruby and so on... CLASHSPATH在jruby等等......

Also, you can implement cheap singletons using global variables (although it's not advisable). 此外,您可以使用全局变量实现廉价单例(尽管不建议)。

So, global variables definitely have a place in Ruby. 因此,全局变量肯定在Ruby中占有一席之地。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM