ruby 中的静态变量,就像在 C 函数中一样
问题描述:
Ruby 中是否有静态变量之类的东西会像在 C 函数中一样?
Is there any such thing as static variables in Ruby that would behave like they do in C functions?
这是我的意思的一个简单示例.它将6\n7\n"打印到控制台.
Here's a quick example of what I mean. It prints "6\n7\n" to the console.
#include <stdio.h>
int test() {
static int a = 5;
a++;
return a;
}
int main() {
printf("%d\n", test());
printf("%d\n", test());
return 0;
}
答
在方法中作用域变量并返回 lambda
Scope your variable in a method and return lambda
def counter
count = 0
lambda{count = count+1}
end
test = counter
test[]
#=>1
test[]
#=>2