像C函数中的静态变量
Ruby中的静态变量是否会像在C函数中那样运行?
这是我的意思的一个简单例子。 它将“6 \ n7 \ n”打印到控制台。
#include int test() { static int a = 5; a++; return a; } int main() { printf("%d\n", test()); printf("%d\n", test()); return 0; }
将变量放在方法中并返回lambda
def counter count = 0 lambda{count = count+1} end test = counter test[] #=>1 test[] #=>2
类似于nicooga的答案,但更独立:
def some_method @var ||= 0 @var += 1 puts @var end
在ruby中,没有变量static
声明,其中变量get绑定到定义它的函数的上下文,但是您可以使用实例变量将变量绑定到对象的上下文。 这就是我将你的代码翻译成ruby的方法:
def test @a ||= 0 # if instance variable @a is not defined, define it as `0` @a += 1 end def print_numbers 2.times { puts test } end
这些函数与全局上下文相关联,但如果用作实例方法,也会起作用。 使用“禁忌”全局变量可以获得类似的结果:
def test $a ||= 0 # if instance variable @a is not defined, define it as `0` $a += 1 end def print_numbers 2.times { puts test } end
但是,在Ruby或任何其他语言中,没有人喜欢全局变量。 很难知道他们在哪里设置。
您可以使用全局变量:
$a = 5 def test $a += 1 end p test #=> 6 p test #=> 7
我认为执行此操作的标准方法是使用Fiber
。
f = Fiber.new do a = 5 loop{Fiber.yield a += 1} end puts f.resume # => 6 puts f.resume # => 7 ...