简体   繁体   中英

Static global C-like variables in Ruby

Does Ruby has static global variables?

With this I mean global variables only accessible from the file where they were defined.

Short answer: No .

The long answer is more complicated.

There's only one global namespace in Ruby and any alterations to it from any code will have the effect of changing it for all code. To keep things local you need to scope them to a particular context, typically module or class . For example:

module PrivateStuff
  @private_variable = "Private (mostly)"

  def self.expose_private_variable
    @private_variable
  end
end

Note this doesn't prevent others from accessing your private variables using instance_variable_get or techniques like that.

This usually isn't a big deal since global variables are usually a sign of bad design and should be avoided unless there's no alternative, a case that's exceedingly rare.

Unlike compiled languages which enforce very strict rules when it comes to data access, Ruby leaves it up to the programmer to be disciplined and simply not do it in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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