如何创建没有命名空间污染的范围



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

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

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

在Javascript中:

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

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

有没有办法在 Ruby 中编写等效项?

你可以做与javascript版本几乎相同的操作

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

请注意,上述和

lambda do
  x = 42
end.call

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

Ruby 变量默认是局部变量。您可以创建具有各种前缀的其他类型的变量:$ 表示全局变量,例如@@@表示类。

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

查看此链接以获取更深入的解释

最新更新