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

时间:2015-03-26 16:25:34

标签: ruby scope local-variables

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

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

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

在Javascript中:

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

i只能看到块或函数范围内的代码,并且没有创建全局命名空间。

有没有办法在Ruby中编写等效的文件?

3 个答案:

答案 0 :(得分:3)

您可以执行与javascript版本

几乎相同的操作
lambda do |;x|
  x = 42
end.call
puts x #=> NameError

请注意,上述和

之间存在细微差别
lambda do
  x = 42
end.call

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

答案 1 :(得分:0)

Ruby变量默认是本地的。您可以使用各种前缀创建其他类型的变量:$表示全局,@表示,@@表示类。

答案 2 :(得分:0)

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以获得更深入的解释