ruby 中的静态变量,就像在 C 函数中一样 [英] Static variables in ruby, like in C functions
本文介绍了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
这篇关于ruby 中的静态变量,就像在 C 函数中一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文