常量变量和全局变量之间的差异

时间:2022-08-08 17:02:40

What is the difference between constant variables and global variables?

常量变量和全局变量之间有什么区别?

CONSTANT = 100
$global = 100

I read this question but I can't understand.

我读了这个问题,但我无法理解。

1 个解决方案

#1


3  

Global variables are global, meaning that even if you put them in a class which is very specifically scoped, they're still available everywhere. They are also explicitly variables (meaning one should not be surprised if their value changes).

全局变量是全局变量,这意味着即使您将它们放在一个非常具体范围的类中,它们仍然可以在任何地方使用。它们也是明确的变量(意思是如果它们的值发生变化,不应该感到惊讶)。

For example:

例如:

module TopLevel
  module MiddleLevel
    module LowLevel
      class SpecificSomething

        $my_global = "duff man says a lot of things"

      end
    end
  end
end


module TopLevel
  def self.global
    p $my_global
  end
end

TopLevel.global   
#=> "duff man says a lot of things"  

Constants are accessible where they are defined - that is, they are NOT global. They are also constants (as the link you provided points out), so one would NOT expect them to change (although ruby does allow them to be changed).

常量可以在定义它们的地方访问 - 也就是说,它们不是全局的。它们也是常量(正如你提供的链接指出的那样),所以人们不会指望它们会改变(尽管ruby确实允许它们被改变)。

#1


3  

Global variables are global, meaning that even if you put them in a class which is very specifically scoped, they're still available everywhere. They are also explicitly variables (meaning one should not be surprised if their value changes).

全局变量是全局变量,这意味着即使您将它们放在一个非常具体范围的类中,它们仍然可以在任何地方使用。它们也是明确的变量(意思是如果它们的值发生变化,不应该感到惊讶)。

For example:

例如:

module TopLevel
  module MiddleLevel
    module LowLevel
      class SpecificSomething

        $my_global = "duff man says a lot of things"

      end
    end
  end
end


module TopLevel
  def self.global
    p $my_global
  end
end

TopLevel.global   
#=> "duff man says a lot of things"  

Constants are accessible where they are defined - that is, they are NOT global. They are also constants (as the link you provided points out), so one would NOT expect them to change (although ruby does allow them to be changed).

常量可以在定义它们的地方访问 - 也就是说,它们不是全局的。它们也是常量(正如你提供的链接指出的那样),所以人们不会指望它们会改变(尽管ruby确实允许它们被改变)。