在Ruby / Rails中使用全局变量或常量变量?

假设我们有与memcache或redis的连接……哪种风格是首选,为什么?

MEMCACHE = Memcache.new(...) REDIS = Redis.new(...) 

要么

 $memcache = Memcache.new(...) $redis = Redis.new(...) 

您可能希望在此处使用Redis.current更多信息

例如,在初始化程序中:

 Redis.current = Redis.new(host: 'localhost', port: 6379) 

然后在你的其他课程中:

 def stars redis.smembers("stars") end private def redis Redis.current end 

它们不是等效的结构。 根据您的应用程序,它们可能是也可能不可互换,但它们在语义上是不同的。

 # MEMCACHE is a constant, subject to scoping constraints. MEMCACHE = Memcache.new(...) # $memcache is a global variable: declare it anywhere; use it anywhere. $memcache = Memcache.new(...) 

IMO是一个“常数”,因为它传达它应该是……不变的。

全球并不意味着它们不应该发生变异。