如何创建没有命名空间污染的作用域

How to create a scope with no namespace pollution

我想定义和使用一些变量而不影响命名空间

例如,在C/C++/Java中:

{
    int i = 42;
    ...
}
int i = 52; // different variable

在Java脚本中:

(function() {
    var i = 42;
    ...
})();
var i = 52; // different variable

i 仅在块或函数范围内的代码可见,并且未创建全局命名空间。

有没有办法在Ruby中写出等价物?

Ruby 变量默认是本地的。您可以创建具有各种前缀的其他类型的变量:$ 用于全局,例如 @@@ 用于 class。

i = 52
def a_function
  puts i
  i = 42
  puts i
end
puts i # this prints 52
# but when you call the function
a_function rescue nil # this will raise an error and catch it with rescue, because a_function cannot access 
           # local variables of the scope where the function is defined
           # which is the main object in this case
           # so a local variable is local to the scope where it was defined but never 
           # be accessible from scopes of other functions


# but this is different if we talk about blocks so if you do this
1.times{ puts i }
# it will print 52
# and a block can also change the value of a local variable
1.times{ i = 60 }
puts i # this prints 60
# functions or methods are not closures in ruby, but blocks, in some sense, are

看看这个 link 以获得更深入的解释

您可以执行与 javascript 版本几乎相同的操作

lambda do |;x|
  x = 42
end.call
puts x #=> NameError

注意上面和

之间有细微的差别
lambda do
  x = 42
end.call

如果外部作用域中没有局部变量x,则两者的行为相同。但是,如果有这样一个局部变量,那么第二个代码片段可以访问它的值,并且更改会影响外部范围,但第一个版本不能做这些事情。